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
sequence | 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.
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
namespace System.Data
{
internal sealed class Select
{
private readonly DataTable _table;
private readonly IndexField[] _indexFields;
private readonly DataViewRowState _recordStates;
private readonly DataExpression _rowFilter;
private readonly ExpressionNode _expression;
private Index _index;
private int[] _records;
private int _recordCount;
private ExpressionNode _linearExpression;
private bool _candidatesForBinarySearch;
private sealed class ColumnInfo
{
public bool flag; // Misc. Use
public bool equalsOperator; // True when the associated expr has = Operator defined
public BinaryNode expr; // Binary Search capable expression associated
}
private ColumnInfo[] _candidateColumns;
private int _nCandidates;
private int _matchedCandidates;
public Select(DataTable table, string filterExpression, string sort, DataViewRowState recordStates)
{
_table = table;
_indexFields = table.ParseSortString(sort);
if (filterExpression != null && filterExpression.Length > 0)
{
_rowFilter = new DataExpression(_table, filterExpression);
_expression = _rowFilter.ExpressionNode;
}
_recordStates = recordStates;
}
private bool IsSupportedOperator(int op)
{
return ((op >= Operators.EqualTo && op <= Operators.LessOrEqual) || op == Operators.Is || op == Operators.IsNot);
}
// Gathers all linear expressions in to this.linearExpression and all binary expressions in to their respective candidate columns expressions
private void AnalyzeExpression(BinaryNode expr)
{
if (_linearExpression == _expression)
return;
if (expr._op == Operators.Or)
{
_linearExpression = _expression;
return;
}
else
if (expr._op == Operators.And)
{
bool isLeft = false, isRight = false;
if (expr._left is BinaryNode)
{
AnalyzeExpression((BinaryNode)expr._left);
if (_linearExpression == _expression)
return;
isLeft = true;
}
else
{
UnaryNode unaryNode = expr._left as UnaryNode;
if (unaryNode != null)
{
while (unaryNode._op == Operators.Noop && unaryNode._right is UnaryNode && ((UnaryNode)unaryNode._right)._op == Operators.Noop)
{
unaryNode = (UnaryNode)unaryNode._right;
}
if (unaryNode._op == Operators.Noop && unaryNode._right is BinaryNode)
{
AnalyzeExpression((BinaryNode)(unaryNode._right));
if (_linearExpression == _expression)
{
return;
}
isLeft = true;
}
}
}
if (expr._right is BinaryNode)
{
AnalyzeExpression((BinaryNode)expr._right);
if (_linearExpression == _expression)
return;
isRight = true;
}
else
{
UnaryNode unaryNode = expr._right as UnaryNode;
if (unaryNode != null)
{
while (unaryNode._op == Operators.Noop && unaryNode._right is UnaryNode && ((UnaryNode)unaryNode._right)._op == Operators.Noop)
{
unaryNode = (UnaryNode)unaryNode._right;
}
if (unaryNode._op == Operators.Noop && unaryNode._right is BinaryNode)
{
AnalyzeExpression((BinaryNode)(unaryNode._right));
if (_linearExpression == _expression)
{
return;
}
isRight = true;
}
}
}
if (isLeft && isRight)
return;
ExpressionNode e = isLeft ? expr._right : expr._left;
_linearExpression = (_linearExpression == null ? e : new BinaryNode(_table, Operators.And, e, _linearExpression));
return;
}
else
if (IsSupportedOperator(expr._op))
{
if (expr._left is NameNode && expr._right is ConstNode)
{
ColumnInfo canColumn = _candidateColumns[((NameNode)(expr._left))._column.Ordinal];
canColumn.expr = (canColumn.expr == null ? expr : new BinaryNode(_table, Operators.And, expr, canColumn.expr));
if (expr._op == Operators.EqualTo)
{
canColumn.equalsOperator = true;
}
_candidatesForBinarySearch = true;
return;
}
else
if (expr._right is NameNode && expr._left is ConstNode)
{
ExpressionNode temp = expr._left;
expr._left = expr._right;
expr._right = temp;
switch (expr._op)
{
case Operators.GreaterThen: expr._op = Operators.LessThen; break;
case Operators.LessThen: expr._op = Operators.GreaterThen; break;
case Operators.GreaterOrEqual: expr._op = Operators.LessOrEqual; break;
case Operators.LessOrEqual: expr._op = Operators.GreaterOrEqual; break;
default: break;
}
ColumnInfo canColumn = _candidateColumns[((NameNode)(expr._left))._column.Ordinal];
canColumn.expr = (canColumn.expr == null ? expr : new BinaryNode(_table, Operators.And, expr, canColumn.expr));
if (expr._op == Operators.EqualTo)
{
canColumn.equalsOperator = true;
}
_candidatesForBinarySearch = true;
return;
}
}
_linearExpression = (_linearExpression == null ? expr : new BinaryNode(_table, Operators.And, expr, _linearExpression));
return;
}
private bool CompareSortIndexDesc(IndexField[] fields)
{
if (fields.Length < _indexFields.Length)
return false;
int j = 0;
for (int i = 0; i < fields.Length && j < _indexFields.Length; i++)
{
if (fields[i] == _indexFields[j])
{
j++;
}
else
{
ColumnInfo canColumn = _candidateColumns[fields[i].Column.Ordinal];
if (!(canColumn != null && canColumn.equalsOperator))
return false;
}
}
return j == _indexFields.Length;
}
private bool FindSortIndex()
{
_index = null;
_table._indexesLock.EnterUpgradeableReadLock();
try
{
int count = _table._indexes.Count;
for (int i = 0; i < count; i++)
{
Index ndx = _table._indexes[i];
if (ndx.RecordStates != _recordStates)
continue;
if (!ndx.IsSharable)
{
continue;
}
if (CompareSortIndexDesc(ndx._indexFields))
{
_index = ndx;
return true;
}
}
}
finally
{
_table._indexesLock.ExitUpgradeableReadLock();
}
return false;
}
// Returns no. of columns that are matched
private int CompareClosestCandidateIndexDesc(IndexField[] fields)
{
int count = (fields.Length < _nCandidates ? fields.Length : _nCandidates);
int i = 0;
for (; i < count; i++)
{
ColumnInfo canColumn = _candidateColumns[fields[i].Column.Ordinal];
if (canColumn == null || canColumn.expr == null)
{
break;
}
else
if (!canColumn.equalsOperator)
{
return i + 1;
}
}
return i;
}
// Returns whether the found index (if any) is a sort index as well
private bool FindClosestCandidateIndex()
{
_index = null;
_matchedCandidates = 0;
bool sortPriority = true;
_table._indexesLock.EnterUpgradeableReadLock();
try
{
int count = _table._indexes.Count;
for (int i = 0; i < count; i++)
{
Index ndx = _table._indexes[i];
if (ndx.RecordStates != _recordStates)
continue;
if (!ndx.IsSharable)
continue;
int match = CompareClosestCandidateIndexDesc(ndx._indexFields);
if (match > _matchedCandidates || (match == _matchedCandidates && !sortPriority))
{
_matchedCandidates = match;
_index = ndx;
sortPriority = CompareSortIndexDesc(ndx._indexFields);
if (_matchedCandidates == _nCandidates && sortPriority)
{
return true;
}
}
}
}
finally
{
_table._indexesLock.ExitUpgradeableReadLock();
}
return (_index != null ? sortPriority : false);
}
// Initialize candidate columns to new columnInfo and leave all non candidate columns to null
private void InitCandidateColumns()
{
_nCandidates = 0;
_candidateColumns = new ColumnInfo[_table.Columns.Count];
if (_rowFilter == null)
return;
DataColumn[] depColumns = _rowFilter.GetDependency();
for (int i = 0; i < depColumns.Length; i++)
{
if (depColumns[i].Table == _table)
{
_candidateColumns[depColumns[i].Ordinal] = new ColumnInfo();
_nCandidates++;
}
}
}
// Based on the required sorting and candidate columns settings, create a new index; Should be called only when there is no existing index to be reused
private void CreateIndex()
{
if (_index == null)
{
if (_nCandidates == 0)
{
_index = new Index(_table, _indexFields, _recordStates, null);
_index.AddRef();
}
else
{
int i;
int lenCanColumns = _candidateColumns.Length;
int lenIndexDesc = _indexFields.Length;
bool equalsOperator = true;
for (i = 0; i < lenCanColumns; i++)
{
if (_candidateColumns[i] != null)
{
if (!_candidateColumns[i].equalsOperator)
{
equalsOperator = false;
break;
}
}
}
int j = 0;
for (i = 0; i < lenIndexDesc; i++)
{
ColumnInfo candidateColumn = _candidateColumns[_indexFields[i].Column.Ordinal];
if (candidateColumn != null)
{
candidateColumn.flag = true;
j++;
}
}
int indexNotInCandidates = lenIndexDesc - j;
IndexField[] ndxFields = new IndexField[_nCandidates + indexNotInCandidates];
if (equalsOperator)
{
j = 0;
for (i = 0; i < lenCanColumns; i++)
{
if (_candidateColumns[i] != null)
{
ndxFields[j++] = new IndexField(_table.Columns[i], isDescending: false);
_candidateColumns[i].flag = false; // this means it is processed
}
}
for (i = 0; i < lenIndexDesc; i++)
{
ColumnInfo canColumn = _candidateColumns[_indexFields[i].Column.Ordinal];
if (canColumn == null || canColumn.flag)
{ // if sort column is not a filter col , or not processed
ndxFields[j++] = _indexFields[i];
if (canColumn != null)
{
canColumn.flag = false;
}
}
}
for (i = 0; i < _candidateColumns.Length; i++)
{
if (_candidateColumns[i] != null)
{
_candidateColumns[i].flag = false; // same as before, it is false when it returns
}
}
// Debug.Assert(j == candidatesNotInIndex, "Whole ndxDesc should be filled!");
_index = new Index(_table, ndxFields, _recordStates, null);
if (!IsOperatorIn(_expression))
{
// if the expression contains an 'IN' operator, the index will not be shared
// therefore we do not need to index.AddRef, also table would track index consuming more memory until first write
_index.AddRef();
}
_matchedCandidates = _nCandidates;
}
else
{
for (i = 0; i < lenIndexDesc; i++)
{
ndxFields[i] = _indexFields[i];
ColumnInfo canColumn = _candidateColumns[_indexFields[i].Column.Ordinal];
if (canColumn != null)
canColumn.flag = true;
}
j = i;
for (i = 0; i < lenCanColumns; i++)
{
if (_candidateColumns[i] != null)
{
if (!_candidateColumns[i].flag)
{
ndxFields[j++] = new IndexField(_table.Columns[i], isDescending: false);
}
else
{
_candidateColumns[i].flag = false;
}
}
}
// Debug.Assert(j == nCandidates+indexNotInCandidates, "Whole ndxDesc should be filled!");
_index = new Index(_table, ndxFields, _recordStates, null);
_matchedCandidates = 0;
if (_linearExpression != _expression)
{
IndexField[] fields = _index._indexFields;
while (_matchedCandidates < j)
{
ColumnInfo canColumn = _candidateColumns[fields[_matchedCandidates].Column.Ordinal];
if (canColumn == null || canColumn.expr == null)
break;
_matchedCandidates++;
if (!canColumn.equalsOperator)
break;
}
}
for (i = 0; i < _candidateColumns.Length; i++)
{
if (_candidateColumns[i] != null)
{
_candidateColumns[i].flag = false; // same as before, it is false when it returns
}
}
}
}
}
}
private bool IsOperatorIn(ExpressionNode enode)
{
BinaryNode bnode = (enode as BinaryNode);
if (null != bnode)
{
if (Operators.In == bnode._op ||
IsOperatorIn(bnode._right) ||
IsOperatorIn(bnode._left))
{
return true;
}
}
return false;
}
// Based on the current index and candidate columns settings, build the linear expression; Should be called only when there is atleast something for Binary Searching
private void BuildLinearExpression()
{
int i;
IndexField[] fields = _index._indexFields;
int lenId = fields.Length;
Debug.Assert(_matchedCandidates > 0 && _matchedCandidates <= lenId, "BuildLinearExpression : Invalid Index");
for (i = 0; i < _matchedCandidates; i++)
{
ColumnInfo canColumn = _candidateColumns[fields[i].Column.Ordinal];
Debug.Assert(canColumn != null && canColumn.expr != null, "BuildLinearExpression : Must be a matched candidate");
canColumn.flag = true;
}
//this is invalid assert, assumption was that all equals operator exists at the beginning of candidateColumns
// but with QFE 1704, this assumption is not true anymore
// Debug.Assert(matchedCandidates==1 || candidateColumns[matchedCandidates-1].equalsOperator, "BuildLinearExpression : Invalid matched candidates");
int lenCanColumns = _candidateColumns.Length;
for (i = 0; i < lenCanColumns; i++)
{
if (_candidateColumns[i] != null)
{
if (!_candidateColumns[i].flag)
{
if (_candidateColumns[i].expr != null)
{
_linearExpression = (_linearExpression == null ? _candidateColumns[i].expr : new BinaryNode(_table, Operators.And, _candidateColumns[i].expr, _linearExpression));
}
}
else
{
_candidateColumns[i].flag = false;
}
}
}
}
public DataRow[] SelectRows()
{
bool needSorting = true;
InitCandidateColumns();
if (_expression is BinaryNode)
{
AnalyzeExpression((BinaryNode)_expression);
if (!_candidatesForBinarySearch)
{
_linearExpression = _expression;
}
if (_linearExpression == _expression)
{
for (int i = 0; i < _candidateColumns.Length; i++)
{
if (_candidateColumns[i] != null)
{
_candidateColumns[i].equalsOperator = false;
_candidateColumns[i].expr = null;
}
}
}
else
{
needSorting = !FindClosestCandidateIndex();
}
}
else
{
_linearExpression = _expression;
}
if (_index == null && (_indexFields.Length > 0 || _linearExpression == _expression))
{
needSorting = !FindSortIndex();
}
if (_index == null)
{
CreateIndex();
needSorting = false;
}
if (_index.RecordCount == 0)
return _table.NewRowArray(0);
Range range;
if (_matchedCandidates == 0)
{
range = new Range(0, _index.RecordCount - 1);
Debug.Assert(!needSorting, "What are we doing here if no real reuse of this index ?");
_linearExpression = _expression;
return GetLinearFilteredRows(range);
}
else
{
range = GetBinaryFilteredRecords();
if (range.Count == 0)
return _table.NewRowArray(0);
if (_matchedCandidates < _nCandidates)
{
BuildLinearExpression();
}
if (!needSorting)
{
return GetLinearFilteredRows(range);
}
else
{
_records = GetLinearFilteredRecords(range);
_recordCount = _records.Length;
if (_recordCount == 0)
return _table.NewRowArray(0);
Sort(0, _recordCount - 1);
return GetRows();
}
}
}
public DataRow[] GetRows()
{
DataRow[] newRows = _table.NewRowArray(_recordCount);
for (int i = 0; i < newRows.Length; i++)
{
newRows[i] = _table._recordManager[_records[i]];
}
return newRows;
}
private bool AcceptRecord(int record)
{
DataRow row = _table._recordManager[record];
if (row == null)
return true;
DataRowVersion version = DataRowVersion.Default;
if (row._oldRecord == record)
{
version = DataRowVersion.Original;
}
else if (row._newRecord == record)
{
version = DataRowVersion.Current;
}
else if (row._tempRecord == record)
{
version = DataRowVersion.Proposed;
}
object val = _linearExpression.Eval(row, version);
bool result;
try
{
result = DataExpression.ToBoolean(val);
}
catch (Exception e) when (ADP.IsCatchableExceptionType(e))
{
throw ExprException.FilterConvertion(_rowFilter.Expression);
}
return result;
}
private int Eval(BinaryNode expr, DataRow row, DataRowVersion version)
{
if (expr._op == Operators.And)
{
int lResult = Eval((BinaryNode)expr._left, row, version);
if (lResult != 0)
return lResult;
int rResult = Eval((BinaryNode)expr._right, row, version);
if (rResult != 0)
return rResult;
return 0;
}
long c = 0;
object vLeft = expr._left.Eval(row, version);
if (expr._op != Operators.Is && expr._op != Operators.IsNot)
{
object vRight = expr._right.Eval(row, version);
bool isLConst = (expr._left is ConstNode);
bool isRConst = (expr._right is ConstNode);
if ((vLeft == DBNull.Value) || (expr._left.IsSqlColumn && DataStorage.IsObjectSqlNull(vLeft)))
return -1;
if ((vRight == DBNull.Value) || (expr._right.IsSqlColumn && DataStorage.IsObjectSqlNull(vRight)))
return 1;
StorageType leftType = DataStorage.GetStorageType(vLeft.GetType());
if (StorageType.Char == leftType)
{
if ((isRConst) || (!expr._right.IsSqlColumn))
vRight = Convert.ToChar(vRight, _table.FormatProvider);
else
vRight = SqlConvert.ChangeType2(vRight, StorageType.Char, typeof(char), _table.FormatProvider);
}
StorageType rightType = DataStorage.GetStorageType(vRight.GetType());
StorageType resultType;
if (expr._left.IsSqlColumn || expr._right.IsSqlColumn)
{
resultType = expr.ResultSqlType(leftType, rightType, isLConst, isRConst, expr._op);
}
else
{
resultType = expr.ResultType(leftType, rightType, isLConst, isRConst, expr._op);
}
if (StorageType.Empty == resultType)
{
expr.SetTypeMismatchError(expr._op, vLeft.GetType(), vRight.GetType());
}
// if comparing a Guid column value against a string literal
// use InvariantCulture instead of DataTable.Locale because in the Danish related cultures
// sorting a Guid as a string has different results than in Invariant and English related cultures.
// This fix is restricted to DataTable.Select("GuidColumn = 'string literal'") types of queries
NameNode namedNode = null;
System.Globalization.CompareInfo comparer =
((isLConst && !isRConst && (leftType == StorageType.String) && (rightType == StorageType.Guid) && (null != (namedNode = expr._right as NameNode)) && (namedNode._column.DataType == typeof(Guid))) ||
(isRConst && !isLConst && (rightType == StorageType.String) && (leftType == StorageType.Guid) && (null != (namedNode = expr._left as NameNode)) && (namedNode._column.DataType == typeof(Guid))))
? System.Globalization.CultureInfo.InvariantCulture.CompareInfo : null;
c = expr.BinaryCompare(vLeft, vRight, resultType, expr._op, comparer);
}
switch (expr._op)
{
case Operators.EqualTo: c = (c == 0 ? 0 : c < 0 ? -1 : 1); break;
case Operators.GreaterThen: c = (c > 0 ? 0 : -1); break;
case Operators.LessThen: c = (c < 0 ? 0 : 1); break;
case Operators.GreaterOrEqual: c = (c >= 0 ? 0 : -1); break;
case Operators.LessOrEqual: c = (c <= 0 ? 0 : 1); break;
case Operators.Is: c = (vLeft == DBNull.Value ? 0 : -1); break;
case Operators.IsNot: c = (vLeft != DBNull.Value ? 0 : 1); break;
default: Debug.Assert(true, "Unsupported Binary Search Operator!"); break;
}
return (int)c;
}
private int Evaluate(int record)
{
DataRow row = _table._recordManager[record];
if (row == null)
return 0;
DataRowVersion version = DataRowVersion.Default;
if (row._oldRecord == record)
{
version = DataRowVersion.Original;
}
else if (row._newRecord == record)
{
version = DataRowVersion.Current;
}
else if (row._tempRecord == record)
{
version = DataRowVersion.Proposed;
}
IndexField[] fields = _index._indexFields;
for (int i = 0; i < _matchedCandidates; i++)
{
int columnOrdinal = fields[i].Column.Ordinal;
Debug.Assert(_candidateColumns[columnOrdinal] != null, "How come this is not a candidate column");
Debug.Assert(_candidateColumns[columnOrdinal].expr != null, "How come there is no associated expression");
int c = Eval(_candidateColumns[columnOrdinal].expr, row, version);
if (c != 0)
return fields[i].IsDescending ? -c : c;
}
return 0;
}
private int FindFirstMatchingRecord()
{
int rec = -1;
int lo = 0;
int hi = _index.RecordCount - 1;
while (lo <= hi)
{
int i = lo + hi >> 1;
int recNo = _index.GetRecord(i);
int c = Evaluate(recNo);
if (c == 0) { rec = i; }
if (c < 0) lo = i + 1;
else hi = i - 1;
}
return rec;
}
private int FindLastMatchingRecord(int lo)
{
int rec = -1;
int hi = _index.RecordCount - 1;
while (lo <= hi)
{
int i = lo + hi >> 1;
int recNo = _index.GetRecord(i);
int c = Evaluate(recNo);
if (c == 0) { rec = i; }
if (c <= 0) lo = i + 1;
else hi = i - 1;
}
return rec;
}
private Range GetBinaryFilteredRecords()
{
if (_matchedCandidates == 0)
{
return new Range(0, _index.RecordCount - 1);
}
Debug.Assert(_matchedCandidates <= _index._indexFields.Length, "GetBinaryFilteredRecords : Invalid Index");
int lo = FindFirstMatchingRecord();
if (lo == -1)
{
return default;
}
int hi = FindLastMatchingRecord(lo);
Debug.Assert(lo <= hi, "GetBinaryFilteredRecords : Invalid Search Results");
return new Range(lo, hi);
}
private int[] GetLinearFilteredRecords(Range range)
{
if (_linearExpression == null)
{
int[] resultRecords = new int[range.Count];
RBTree<int>.RBTreeEnumerator iterator = _index.GetEnumerator(range.Min);
for (int i = 0; i < range.Count && iterator.MoveNext(); i++)
{
resultRecords[i] = iterator.Current;
}
return resultRecords;
}
else
{
List<int> matchingRecords = new List<int>();
RBTree<int>.RBTreeEnumerator iterator = _index.GetEnumerator(range.Min);
for (int i = 0; i < range.Count && iterator.MoveNext(); i++)
{
if (AcceptRecord(iterator.Current))
{
matchingRecords.Add(iterator.Current);
}
}
return matchingRecords.ToArray();
}
}
private DataRow[] GetLinearFilteredRows(Range range)
{
DataRow[] resultRows;
if (_linearExpression == null)
{
return _index.GetRows(range);
}
List<DataRow> matchingRows = new List<DataRow>();
RBTree<int>.RBTreeEnumerator iterator = _index.GetEnumerator(range.Min);
for (int i = 0; i < range.Count && iterator.MoveNext(); i++)
{
if (AcceptRecord(iterator.Current))
{
matchingRows.Add(_table._recordManager[iterator.Current]);
}
}
resultRows = _table.NewRowArray(matchingRows.Count);
matchingRows.CopyTo(resultRows);
return resultRows;
}
private int CompareRecords(int record1, int record2)
{
int lenIndexDesc = _indexFields.Length;
for (int i = 0; i < lenIndexDesc; i++)
{
int c = _indexFields[i].Column.Compare(record1, record2);
if (c != 0)
{
if (_indexFields[i].IsDescending) c = -c;
return c;
}
}
long id1 = _table._recordManager[record1] == null ? 0 : _table._recordManager[record1].rowID;
long id2 = _table._recordManager[record2] == null ? 0 : _table._recordManager[record2].rowID;
int diff = (id1 < id2) ? -1 : ((id2 < id1) ? 1 : 0);
// if they're two records in the same row, we need to be able to distinguish them.
if (diff == 0 && record1 != record2 &&
_table._recordManager[record1] != null && _table._recordManager[record2] != null)
{
id1 = (int)_table._recordManager[record1].GetRecordState(record1);
id2 = (int)_table._recordManager[record2].GetRecordState(record2);
diff = (id1 < id2) ? -1 : ((id2 < id1) ? 1 : 0);
}
return diff;
}
private void Sort(int left, int right)
{
int i, j;
int record;
do
{
i = left;
j = right;
record = _records[i + j >> 1];
do
{
while (CompareRecords(_records[i], record) < 0) i++;
while (CompareRecords(_records[j], record) > 0) j--;
if (i <= j)
{
int r = _records[i];
_records[i] = _records[j];
_records[j] = r;
i++;
j--;
}
} while (i <= j);
if (left < j) Sort(left, j);
left = i;
} while (i < right);
}
}
}
| 39.608549 | 217 | 0.448455 | [
"MIT"
] | 71221-maker/runtime | src/libraries/System.Data.Common/src/System/Data/Select.cs | 35,212 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2017 Henk-Jan Lebbink
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using Microsoft.Z3;
using System;
using System.Collections.Generic;
namespace AsmSim
{
public static class ToolsFloatingPoint
{
public static IEnumerable<FPExpr> BV_2_Doubles(BitVecExpr value, Context ctx)
{
uint nBits = value.SortSize;
if (nBits == 128)
{
uint pos = nBits;
{
BitVecExpr sgn = ctx.MkExtract(pos - 1, pos - 1, value);
BitVecExpr sig = ctx.MkExtract(pos - 2, pos - 13, value);
BitVecExpr exp = ctx.MkExtract(pos - 14, pos - 64, value);
yield return ctx.MkFP(sgn, sig, exp);
}
pos -= 64;
{
BitVecExpr sgn = ctx.MkExtract(pos - 1, pos - 1, value);
BitVecExpr sig = ctx.MkExtract(pos - 2, pos - 13, value);
BitVecExpr exp = ctx.MkExtract(pos - 14, pos - 64, value);
yield return ctx.MkFP(sgn, sig, exp);
}
} else if (nBits == 256)
{
} else if (nBits == 512)
{
}
else
{
throw new Exception();
}
}
public static BitVecExpr FP_2_BV(IEnumerable<FPExpr> fps, Context ctx)
{
BitVecExpr result = null;
foreach (FPExpr fp in fps)
{
result = (result == null) ? ctx.MkFPToIEEEBV(fp) : ctx.MkConcat(result, ctx.MkFPToIEEEBV(fp));
}
return result;
}
}
}
| 37.520548 | 110 | 0.586345 | [
"MIT"
] | 864430457/asm-dude | VS/CSHARP/asm-sim-lib/ToolsFloatingPoint.cs | 2,741 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18047
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace x360NANDManagerGUI.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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 | 151 | 0.584343 | [
"Unlicense"
] | KirovAir/x360NANDManager | x360NANDManagerGUI/x360NANDManagerGUI/Properties/Settings.Designer.cs | 1,075 | C# |
//Write a program to convert hexadecimal numbers to binary numbers (directly).
using System;
class HexToBinConverter
{
static void Main()
{
string input = Console.ReadLine();
string result = string.Empty;
for (int i = input.Length - 1; i >= 0; i--)
{
switch (input[i])
{
case '0':
result = "0000" + result;
break;
case '1':
result = "0001" + result;
break;
case '2':
result = "0010" + result;
break;
case '3':
result = "0011" + result;
break;
case '4':
result = "0100" + result;
break;
case '5':
result = "0101" + result;
break;
case '6':
result = "0110" + result;
break;
case '7':
result = "0111" + result;
break;
case '8':
result = "1000" + result;
break;
case '9':
result = "1001" + result;
break;
case 'A':
result = "1010" + result;
break;
case 'B':
result = "1011" + result;
break;
case 'C':
result = "1100" + result;
break;
case 'D':
result = "1101" + result;
break;
case 'E':
result = "1110" + result;
break;
case 'F':
result = "1111" + result;
break;
default:
break;
}
}
Console.WriteLine(result);
}
}
| 28 | 79 | 0.314579 | [
"MIT"
] | mdraganov/Telerik-Academy | C#/C# Programming Part II/NumeralSystems/05.HexadecimalToBinary/HexToBinConverter.cs | 2,046 | C# |
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace EFCore.BulkExtensions
{
public class FastProperty
{
public FastProperty(PropertyInfo property)
{
Property = property;
InitializeGet();
InitializeSet();
}
private void InitializeSet()
{
var instance = Expression.Parameter(typeof(object), "instance");
var value = Expression.Parameter(typeof(object), "value");
UnaryExpression instanceCast = (!Property.DeclaringType.IsValueType) ? Expression.TypeAs(instance, Property.DeclaringType) : Expression.Convert(instance, Property.DeclaringType);
UnaryExpression valueCast = (!Property.PropertyType.IsValueType) ? Expression.TypeAs(value, Property.PropertyType) : Expression.Convert(value, Property.PropertyType);
SetDelegate = Expression.Lambda<Action<object, object>>(Expression.Call(instanceCast, Property.GetSetMethod(true), valueCast), new ParameterExpression[] { instance, value }).Compile();
}
private void InitializeGet()
{
var instance = Expression.Parameter(typeof(object), "instance");
UnaryExpression instanceCast = (!Property.DeclaringType.IsValueType) ? Expression.TypeAs(instance, Property.DeclaringType) : Expression.Convert(instance, Property.DeclaringType);
GetDelegate = Expression.Lambda<Func<object, object>>(Expression.TypeAs(Expression.Call(instanceCast, Property.GetGetMethod(true)), typeof(object)), instance).Compile();
}
public PropertyInfo Property { get; set; }
public Func<object, object> GetDelegate;
public Action<object, object> SetDelegate;
public object Get(object instance) { return GetDelegate(instance); }
public void Set(object instance, object value) { SetDelegate(instance, value); }
}
}
| 44.534884 | 196 | 0.688251 | [
"MIT"
] | jr01/EFCore.BulkExtensions | EFCore.BulkExtensions/FastProperty.cs | 1,917 | 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.IO;
using Xunit;
namespace System.Reflection.PortableExecutable.Tests
{
public class BadImageFormat
{
[Fact]
public void InvalidSectionCount()
{
var pe = new MemoryStream(new byte[] {
0xd0, 0xcf, 0x11, 0xe0, 0xa1,
0xb1, 0x1a, 0xe1, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00,
});
Assert.Throws<BadImageFormatException>(() => new PEHeaders(pe));
}
}
}
| 27.384615 | 101 | 0.570225 | [
"MIT"
] | 690486439/corefx | src/System.Reflection.Metadata/tests/PortableExecutable/BadImageFormat.cs | 712 | C# |
// Copyright 2017 Cvent, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
namespace SolutionAudit
{
static class Utils
{
public static IEnumerable<T> Closure<T>(T root, Func<T, IEnumerable<T>> children)
{
var seen = new HashSet<T>();
var stack = new Stack<T>();
stack.Push(root);
while (stack.Count != 0)
{
var item = stack.Pop();
if (!seen.Add(item)) continue;
yield return item;
foreach (var child in children(item))
{
stack.Push(child);
}
}
}
public static IEnumerable<TSource> Duplicates<TSource>(this IEnumerable<TSource> enumerable)
{
return enumerable.DuplicatesBy(s => s);
}
public static IEnumerable<TSource> DuplicatesBy<TSource, TKey>(this IEnumerable<TSource> enumerable,
Func<TSource, TKey> keySelector)
{
return enumerable.GroupBy(keySelector).SelectMany(g => g.Skip(1));
}
public static bool AllEqual<T>(this IEnumerable<T> enumerable)
{
return enumerable.Distinct().Count() == 1;
}
}
public abstract class Wrapper<T>
{
protected Wrapper(T wrapped)
{
Wrapped = wrapped;
}
protected T Wrapped { get; set; }
}
public interface IVisualStudioCommand
{
string VsCommand();
}
}
| 28.726027 | 108 | 0.591321 | [
"Apache-2.0"
] | cvent/solution-audit | SolutionAudit/Utils.cs | 2,097 | C# |
using System.Collections.Generic;
using Essensoft.Paylink.Alipay.Response;
namespace Essensoft.Paylink.Alipay.Request
{
/// <summary>
/// alipay.open.lottery.camp.offline
/// </summary>
public class AlipayOpenLotteryCampOfflineRequest : IAlipayRequest<AlipayOpenLotteryCampOfflineResponse>
{
/// <summary>
/// 天天抽奖-活动下架
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.open.lottery.camp.offline";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.524194 | 107 | 0.544576 | [
"MIT"
] | fory77/paylink | src/Essensoft.Paylink.Alipay/Request/AlipayOpenLotteryCampOfflineRequest.cs | 2,811 | C# |
using System.IO;
using OpenQA.Selenium.Chrome;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Saber.Vendor;
namespace Saber.Vendors.Screenshot
{
public class Startup : IVendorStartup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfigurationRoot config)
{
var path = App.MapPath("/Content/screenshots");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var options = new ChromeOptions();
options.AddArgument("headless");
WebDriver.Chrome = new ChromeDriver(App.MapPath("/Vendors/Screenshot/"), options);
}
}
}
| 29 | 107 | 0.645474 | [
"Apache-2.0"
] | Datasilk/Saber-Screenshot | Startup.cs | 930 | C# |
using System.Collections.Generic;
using Game;
using Tools;
using UI.Show;
using UnityEngine;
using UnityEngine.UI;
namespace UI
{
public class WindowTabBuilder : MonoBehaviour, IWindow
{
private List<Tab> _tabs;
private string _title;
public Text header;
public GameObject content;
public GameObject tabList;
/// <summary>
/// Use the create method
/// </summary>
private WindowTabBuilder(){}
public static WindowTabBuilder Create(string title)
{
title = TextHelper.Cap(title);
GameObject act = Instantiate(UIElements.Get().tabWindow, GameObject.Find("WindowsMgmt").transform);
act.name = title;
act.GetComponent<WindowTabBuilder>().Init(title);
return act.GetComponent<WindowTabBuilder>();
}
public static WindowTabBuilder CreateT(string title)
{
return Create(S.T(title));
}
private void Init(string title)
{
_tabs = new List<Tab>();
_title = title;
header.text = title;
}
public void Add(Tab tab)
{
_tabs.Add(tab);
tab.window = this;
}
public void Finish()
{
//build tabs
foreach (Tab t in _tabs)
{
UIElements.CreateImageButton(t.Icon(), tabList.transform, () => { ShowTab(t); });
}
//show first tab?
if (_tabs.Count > 0)
{
ShowTab(_tabs[0]);
}
gameObject.SetActive(true);
}
public int Count()
{
return _tabs.Count;
}
public void CloseWindow()
{
Destroy(gameObject);
}
public void ShowTab(Tab t)
{
header.text = $"{_title} | {t.Name()}";
UIHelper.ClearChild(content);
t.Show(content.transform);
}
public void ShowTab(int t)
{
ShowTab(_tabs[t]);
}
}
} | 24.067416 | 111 | 0.498599 | [
"MIT"
] | TrutzX/9Nations | Assets/Scripts/UI/WindowTabBuilder.cs | 2,142 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using LiveLisp.Core.AST.Expressions.CLR;
using LiveLisp.Core.Compiler;
namespace LiveLisp.Core.Runtime.OperatorsCache
{
public static class GeneralHelpers
{
private static MethodInfo _EqualsMethod = typeof(object).GetMethod("Equals", BindingFlags.Public|BindingFlags.Static);
public static object GetAndInvokeTarget2(Dictionary<Type, Dictionary<Type, BinaryOperator>> _cache, Operator op, object arg1, object arg2)
{
Dictionary<Type, BinaryOperator> val;
Type arg1Type = arg1.GetType();
Type arg2Type = arg2.GetType();
// bool arithmetic = IsArithmetic(arg1Type) && IsArithmetic(arg2Type);
BinaryOperator target;
if (_cache.TryGetValue(arg1Type, out val))
{
if (val.TryGetValue(arg2Type, out target))
{
return target(arg1, arg2);
}
}
if (_cache.TryGetValue(arg2Type, out val))
{
if (val.TryGetValue(arg1Type, out target))
{
return target(arg2, arg1);
}
}
bool swap_args;
target = GeneralHelpers.MakeNewBinaryOpTarget(op, arg1Type, arg2Type, out swap_args);
if (swap_args)
{
Type tmp = arg1Type;
arg1Type = arg2Type;
arg2Type = tmp;
}
Dictionary<Type, BinaryOperator> newDictionary;
if (!_cache.TryGetValue(arg1Type, out newDictionary))
{
newDictionary = new Dictionary<Type, BinaryOperator>();
_cache.Add(arg1Type, newDictionary);
}
newDictionary.Add(arg2Type, target);
if (swap_args)
return target(arg2, arg1);
return target(arg1, arg2);
}
public static BinaryOperator MakeNewBinaryOpTarget(Operator op, Type arg1Type, Type arg2Type, out bool swap_args)
{
bool both_a = GeneralHelpers.IsArithmetic(arg1Type) && GeneralHelpers.IsArithmetic(arg2Type);
if (IsOpArithmetic(op) && both_a)
{
swap_args = false;
return GeneralHelpers.EmitSimpleArithmeticOp(op, arg1Type, arg2Type);
}
else if (IsComparisonOp(op) && both_a)
{
swap_args = false;
return GeneralHelpers.EmitSimpleComparisonOp(op, arg1Type, arg2Type, true);
}
else
{
return GeneralHelpers.EmitCustomBinaryOp(op, arg1Type, arg2Type, true, out swap_args);
}
}
private static bool IsOpArithmetic(Operator op)
{
switch (op)
{
case Operator.Add:
case Operator.Sub:
case Operator.Mul:
case Operator.Div:
return true;
case Operator.LessThen:
case Operator.GreaterThen:
case Operator.LessOrEqual:
case Operator.GreaterOrEqual:
case Operator.Equal:
case Operator.NotEqual:
return false;
default:
throw new NotImplementedException();
}
}
private static bool IsComparisonOp(Operator op)
{
switch (op)
{
case Operator.Add:
case Operator.Sub:
case Operator.Mul:
case Operator.Div:
return false;
case Operator.LessThen:
case Operator.GreaterThen:
case Operator.LessOrEqual:
case Operator.GreaterOrEqual:
case Operator.Equal:
case Operator.NotEqual:
return true;
default:
throw new NotImplementedException();
}
}
public static BinaryOperator EmitSimpleArithmeticOp(Operator op, Type arg1Type, Type arg2Type)
{
DynamicMethod new_Target = new DynamicMethod("AddOp" + arg1Type.Name + arg2Type.Name, typeof(object), new Type[] { typeof(object), typeof(object) });
Type upgradet = GeneralHelpers.UpgradeToType1(arg1Type, arg2Type);
Type upgradet1 = GeneralHelpers.UpgradeToType2(arg1Type, arg2Type);
ILGenerator gen = new_Target.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Unbox_Any, arg1Type);
if (op == Operator.Div && (upgradet == typeof(int) || upgradet == typeof(long)))
upgradet = typeof(double);
if (upgradet != arg1Type)
gen.EmitNumericConversion(arg1Type, upgradet, false);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Unbox_Any, arg2Type);
if (op == Operator.Div && (upgradet1 == typeof(int) || upgradet1 == typeof(long)))
upgradet1 = typeof(double);
if (upgradet1 != arg2Type)
gen.EmitNumericConversion(arg2Type, upgradet1, false);
Type retType = GeneralHelpers.SimpleArithmeticResultType(upgradet, upgradet1);
switch (op)
{
case Operator.Add:
if (upgradet == typeof(int))
gen.EmitCall(RuntimeHelpers.Int32AddMethod.Method);
else if(upgradet == typeof(long))
gen.EmitCall(RuntimeHelpers.Int64AddMethod.Method);
else
gen.Emit(OpCodes.Add);
break;
case Operator.Sub:
if (upgradet == typeof(int))
gen.EmitCall(RuntimeHelpers.Int32SubMethod.Method);
else if (upgradet == typeof(long))
gen.EmitCall(RuntimeHelpers.Int64SubMethod.Method);
else
gen.Emit(OpCodes.Sub);
break;
case Operator.Mul:
if (upgradet == typeof(int))
gen.EmitCall(RuntimeHelpers.Int32MulMethod.Method);
else if (upgradet == typeof(long))
gen.EmitCall(RuntimeHelpers.Int64MulMethod.Method);
else
gen.Emit(OpCodes.Mul);
break;
case Operator.Div:
if (upgradet == typeof(int))
gen.EmitCall(RuntimeHelpers.Int32DivMethod.Method);
else if (upgradet == typeof(long))
gen.EmitCall(RuntimeHelpers.Int64DivMethod.Method);
else
gen.Emit(OpCodes.Div);
break;
default:
throw new NotImplementedException();
}
if (upgradet != typeof(int) && upgradet != typeof(long))
{
gen.Emit(OpCodes.Box, retType);
}
gen.Emit(OpCodes.Ret);
return new_Target.CreateDelegate(typeof(BinaryOperator)) as BinaryOperator;
}
private static BinaryOperator EmitSimpleComparisonOp(Operator op, Type arg1Type, Type arg2Type, bool convert_to_lisp)
{
DynamicMethod new_Target = new DynamicMethod("AddOp" + arg1Type.Name + arg2Type.Name, typeof(object), new Type[] { typeof(object), typeof(object) });
Type upgradet = GeneralHelpers.UpgradeToType1(arg1Type, arg2Type);
Type upgradet1 = GeneralHelpers.UpgradeToType2(arg1Type, arg2Type);
ILGenerator gen = new_Target.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Unbox_Any, arg1Type);
if (upgradet != arg1Type)
gen.EmitNumericConversion(arg1Type, upgradet, false);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Unbox_Any, arg2Type);
if (upgradet != arg2Type)
gen.EmitNumericConversion(arg1Type, upgradet, false);
switch (op)
{
case Operator.LessThen:
gen.Emit(OpCodes.Clt);
break;
case Operator.GreaterThen:
gen.Emit(OpCodes.Cgt);
break;
case Operator.LessOrEqual:
gen.Emit(OpCodes.Cgt);
gen.Emit(OpCodes.Ldc_I4_0);
gen.Emit(OpCodes.Ceq);
break;
case Operator.GreaterOrEqual:
gen.Emit(OpCodes.Clt);
gen.Emit(OpCodes.Ldc_I4_0);
gen.Emit(OpCodes.Ceq);
break;
case Operator.Equal:
gen.Emit(OpCodes.Ceq);
break;
case Operator.NotEqual:
gen.Emit(OpCodes.Ceq);
gen.Emit(OpCodes.Ldc_I4_0);
gen.Emit(OpCodes.Ceq);
break;
default:
throw new NotImplementedException();
}
if (convert_to_lisp)
{
Label else_label = gen.DefineLabel();
Label end_label = gen.DefineLabel();
gen.Emit(OpCodes.Brfalse, else_label);
gen.EmitT();
gen.JmpToLabel(end_label);
gen.MarkLabel(else_label);
gen.EmitNIL();
gen.MarkLabel(end_label);
}
else
{
gen.Emit(OpCodes.Box, typeof(Boolean));
}
gen.Emit(OpCodes.Ret);
return new_Target.CreateDelegate(typeof(BinaryOperator)) as BinaryOperator;
}
public static BinaryOperator EmitCustomBinaryOp(Operator op, Type arg1Type, Type arg2Type, bool convert_to_lisp, out bool swap_args)
{
swap_args = false;
MethodInfo op_method = GetCustomBinaryOperator(op, arg1Type, arg2Type, ref swap_args);
if (op_method == null)
throw new OperatorNotFoundException("The binary operator {0} is not defined for the types '{1}' and '{2}'.", OpDisplayName(op), arg1Type, arg2Type);
if (swap_args)
{
Type tmp = arg1Type;
arg1Type = arg2Type;
arg2Type = tmp;
}
DynamicMethod new_Target = new DynamicMethod(OpDisplayName(op) + " " + arg1Type.Name + arg2Type.Name, typeof(object), new Type[] { typeof(object), typeof(object) });
ILGenerator gen = new_Target.GetILGenerator();
var parms = op_method.GetParameters();
gen.Emit(OpCodes.Ldarg_0);
if (parms[0].ParameterType.IsValueType)
{
gen.Emit(OpCodes.Unbox_Any, arg1Type);
}
else
{
gen.Emit(OpCodes.Isinst, arg1Type);
}
gen.Emit(OpCodes.Ldarg_1);
if (parms[1].ParameterType.IsValueType)
{
gen.Emit(OpCodes.Unbox_Any, arg2Type);
}
else
{
gen.Emit(OpCodes.Isinst, arg2Type);
}
gen.Emit(OpCodes.Call, op_method);
if (convert_to_lisp)
{
if (op_method.ReturnType == typeof(Boolean))
{
Label else_label = gen.DefineLabel();
Label end_label = gen.DefineLabel();
gen.Emit(OpCodes.Brfalse, else_label);
gen.EmitT();
gen.JmpToLabel(end_label);
gen.MarkLabel(else_label);
gen.EmitNIL();
gen.MarkLabel(end_label);
}
else
{
if (op_method.ReturnType.IsValueType)
{
gen.Emit(OpCodes.Box, op_method.ReturnType);
}
}
}
else
{
if (op_method.ReturnType.IsValueType)
{
gen.Emit(OpCodes.Box, op_method.ReturnType);
}
}
gen.EmitRet();
return new_Target.CreateDelegate(typeof(BinaryOperator)) as BinaryOperator;
}
private static string OpDisplayName(Operator op)
{
switch (op)
{
case Operator.Add:
return "Add";
case Operator.Sub:
return "Sub";
case Operator.Mul:
return "Mul";
case Operator.Div:
return "Div";
case Operator.LessThen:
return "LessThen";
case Operator.GreaterThen:
return "GreateThen";
case Operator.LessOrEqual:
return "LessOrEqual";
case Operator.GreaterOrEqual:
return "GreaterOrEqual";
case Operator.Equal:
return "Equal";
case Operator.NotEqual:
return "NotEqual";
default:
throw new NotImplementedException();
}
}
private static string OpMethodName(Operator op)
{
switch (op)
{
case Operator.Add:
return "op_Addition";
case Operator.Sub:
return "op_Subtraction";
case Operator.Mul:
return "op_Multiply";
case Operator.Div:
return "op_Division";
case Operator.LessThen:
return "op_LessThen";
case Operator.GreaterThen:
return "op_GreaterThen";
case Operator.LessOrEqual:
return "op_GreaterThanOrEqual";
case Operator.GreaterOrEqual:
return "op_LessThanOrEqual";
case Operator.Equal:
return "op_Equality";
case Operator.NotEqual:
return "op_Inequality";
default:
throw new NotImplementedException();
}
}
public static MethodInfo GetCustomBinaryOperator(Operator op, Type arg1Type, Type arg2Type, ref bool swap_args)
{
MethodInfo method = null;
string m_name = OpMethodName(op);
try
{
method = arg1Type.GetMethod(m_name, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { arg1Type, arg2Type }, null);
if (method != null)
return method;
}
catch (AmbiguousMatchException)
{
}
try
{
method = arg1Type.GetMethod(m_name, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { arg2Type, arg1Type }, null);
if (method != null)
{
swap_args = true;
return method;
}
}
catch (AmbiguousMatchException)
{
}
try
{
method = arg2Type.GetMethod(m_name, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { arg1Type, arg2Type }, null);
if (method != null)
return method;
}
catch (AmbiguousMatchException)
{
}
try
{
method = arg2Type.GetMethod(m_name, BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { arg2Type, arg1Type }, null);
if (method != null)
{
swap_args = true;
return method;
}
}
catch (AmbiguousMatchException)
{
}
//check for conversion possibilities
// equality patch - if op is Equality or Inequality operator and method == null;
// replace with object.Equals call
if (method == null && (op == Operator.Equal || op == Operator.NotEqual))
{
return _EqualsMethod;
}
return method;
}
public static Type SimpleArithmeticResultType(Type ca1, Type ca2)
{
TypeCode tc1 = Type.GetTypeCode(ca1);
TypeCode tc2 = Type.GetTypeCode(ca2);
switch (tc1)
{
case TypeCode.Double:
return ca1;
case TypeCode.Int32:
switch (tc2)
{
case TypeCode.Double:
return ca2;
case TypeCode.Int32:
return ca1;
case TypeCode.Int64:
return ca2;
case TypeCode.Single:
return ca2;
}
break;
case TypeCode.Int64:
switch (tc2)
{
case TypeCode.Double:
return ca2;
case TypeCode.Int32:
return ca1;
case TypeCode.Int64:
return ca1;
case TypeCode.Single:
return ca2;
}
break;
case TypeCode.Single:
switch (tc2)
{
case TypeCode.Double:
return ca2;
case TypeCode.Int32:
return ca1;
case TypeCode.Int64:
return ca1;
case TypeCode.Single:
return ca1;
}
break;
}
throw new Exception();
}
public static Type UpgradeToType2(Type arg1Type, Type arg2Type)
{
Type ca1 = UpgradeCLRType(arg1Type);
Type ca2 = UpgradeCLRType(arg2Type);
if (ca1 == ca2)
return ca1;
TypeCode tc1 = Type.GetTypeCode(ca1);
TypeCode tc2 = Type.GetTypeCode(ca2);
switch (tc1)
{
case TypeCode.Double:
return ca1;
case TypeCode.Int32:
switch (tc2)
{
case TypeCode.Double:
return ca2;
case TypeCode.Int32:
return ca1;
case TypeCode.Int64:
return ca2;
case TypeCode.Single:
return ca2;
}
break;
case TypeCode.Int64:
switch (tc2)
{
case TypeCode.Double:
return ca2;
case TypeCode.Int32:
return ca1;
case TypeCode.Int64:
return ca1;
case TypeCode.Single:
return ca2;
}
break;
case TypeCode.Single:
switch (tc2)
{
case TypeCode.Double:
return ca2;
case TypeCode.Int32:
return ca1;
case TypeCode.Int64:
return ca1;
case TypeCode.Single:
return ca1;
}
break;
}
throw new Exception();
}
public static Type UpgradeToType1(Type arg1Type, Type arg2Type)
{
return UpgradeToType2(arg2Type, arg1Type);
}
public static Type UpgradeCLRType(Type argType)
{
TypeCode tc = Type.GetTypeCode(argType);
switch (tc)
{
case TypeCode.Boolean:
return typeof(Int32);
case TypeCode.Byte:
return typeof(Int32);
case TypeCode.Char:
return typeof(Int32);
case TypeCode.DBNull:
break;
case TypeCode.DateTime:
break;
case TypeCode.Decimal:
break;
case TypeCode.Double:
return typeof(Double);
case TypeCode.Empty:
break;
case TypeCode.Int16:
return typeof(Int32);
case TypeCode.Int32:
return typeof(Int32);
case TypeCode.Int64:
return typeof(Int64);
case TypeCode.Object:
break;
case TypeCode.SByte:
return typeof(Int32);
case TypeCode.Single:
return typeof(Single);
case TypeCode.String:
break;
case TypeCode.UInt16:
return typeof(Int32);
case TypeCode.UInt32:
return typeof(Int64);
case TypeCode.UInt64:
return typeof(Single);
default:
break;
}
throw new ArgumentException("type " + argType + " is not simple numeric type");
}
internal static Type GetNonNullableType(Type type)
{
if (IsNullableType(type))
{
return type.GetGenericArguments()[0];
}
return type;
}
//CONFORMING
internal static Type GetNullableType(Type type)
{
System.Diagnostics.Debug.Assert(type != null, "type cannot be null");
if (type.IsValueType && !IsNullableType(type))
{
return typeof(Nullable<>).MakeGenericType(type);
}
return type;
}
//CONFORMING
internal static bool IsNullableType(this Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
internal static bool IsArithmetic(Type type)
{
type = GetNonNullableType(type);
if (!type.IsEnum)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return true;
}
}
return false;
}
}
}
| 34.655072 | 177 | 0.46416 | [
"MIT"
] | deadtrickster/LiveLisp | LiveLisp.Core/Runtime/OperatorsCache/GeneralHelpers.cs | 23,914 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Network;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Parameters that define a resource to query flow log status.
/// </summary>
public partial class FlowLogStatusParameters
{
/// <summary>
/// Initializes a new instance of the FlowLogStatusParameters class.
/// </summary>
public FlowLogStatusParameters()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the FlowLogStatusParameters class.
/// </summary>
/// <param name="targetResourceId">The target resource where getting
/// the flow logging status.</param>
public FlowLogStatusParameters(string targetResourceId)
{
TargetResourceId = targetResourceId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the target resource where getting the flow logging
/// status.
/// </summary>
[JsonProperty(PropertyName = "targetResourceId")]
public string TargetResourceId { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (TargetResourceId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "TargetResourceId");
}
}
}
}
| 31.565217 | 96 | 0.613407 | [
"MIT"
] | azure-keyvault/azure-sdk-for-net | src/SDKs/Network/Management.Network/Generated/Models/FlowLogStatusParameters.cs | 2,178 | C# |
// dnlib: See LICENSE.txt for more info
using System.Diagnostics;
using System.Text;
namespace dnlib.DotNet.Pdb.Symbols {
/// <summary>
/// Sequence point
/// </summary>
[DebuggerDisplay("{GetDebuggerString(),nq}")]
public struct SymbolSequencePoint {
/// <summary>
/// IL offset
/// </summary>
public int Offset;
/// <summary>
/// Document
/// </summary>
public SymbolDocument Document;
/// <summary>
/// Start line
/// </summary>
public int Line;
/// <summary>
/// Start column
/// </summary>
public int Column;
/// <summary>
/// End line
/// </summary>
public int EndLine;
/// <summary>
/// End column
/// </summary>
public int EndColumn;
string GetDebuggerString() {
var sb = new StringBuilder();
if (Line == 0xFEEFEE && EndLine == 0xFEEFEE)
sb.Append("<hidden>");
else {
sb.Append("(");
sb.Append(Line);
sb.Append(",");
sb.Append(Column);
sb.Append(")-(");
sb.Append(EndLine);
sb.Append(",");
sb.Append(EndColumn);
sb.Append(")");
}
sb.Append(": ");
sb.Append(Document.URL);
return sb.ToString();
}
}
}
| 18.031746 | 47 | 0.581866 | [
"MIT"
] | KevOrr/dnlib | src/DotNet/Pdb/Symbols/SymbolSequencePoint.cs | 1,138 | C# |
using NetORMLib.Columns;
using NetORMLib.Tables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PIO.ServerLib.Tables
{
public class PlanetTable : Table
{
public static readonly Column<int> PlanetID = new Column<int>() { Constraint = NetORMLib.ColumnConstraints.PrimaryKey, IsIdentity = true };
public new static readonly Column<string> Name = new Column<string>() { DefaultValue = "New planet" };
public static readonly Column<int> Width = new Column<int>() { DefaultValue = 50 };
public static readonly Column<int> Height = new Column<int>() { DefaultValue = 50 };
}
}
| 34.842105 | 141 | 0.747734 | [
"MIT"
] | dfgs/PIO | PIO.ServerLib/Tables/PlanetTable.cs | 664 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using ProSuite.Commons.Essentials.Assertions;
using ProSuite.Commons.Essentials.CodeAnnotations;
using ProSuite.Commons.Exceptions;
using ProSuite.Commons.Logging;
using ProSuite.DomainModel.Core;
using ProSuite.DomainModel.Core.DataModel;
using ProSuite.DomainModel.Core.Processing;
using ProSuite.DomainModel.Core.Processing.Reporting;
namespace ProSuite.DomainModel.AO.Processing
{
/// <summary>
/// A container for static utility methods related to GdbProcesses.
/// </summary>
public static class CartoProcessUtils
{
private static readonly IMsg _msg =
new Msg(MethodBase.GetCurrentMethod().DeclaringType);
[NotNull]
public static IList<PropertyInfo> GetProcessParameters(
[NotNull] CartoProcessType cartoProcessType)
{
Assert.ArgumentNotNull(cartoProcessType, nameof(cartoProcessType));
Type type = cartoProcessType.CartoProcessClassDescriptor.GetInstanceType();
return GdbProcessUtils.GetProcessParameters(type);
}
[NotNull]
public static IGdbProcess CreateGdbProcess([NotNull] CartoProcess template)
{
Assert.ArgumentNotNull(template, nameof(template));
CartoProcessType cartoProcessType = template.CartoProcessType;
Type t = cartoProcessType.CartoProcessClassDescriptor.GetInstanceType();
var process = (IGdbProcess) Activator.CreateInstance(t);
Assert.NotNull(process, "process");
process.Name = template.Name;
process.Description = template.Description;
Type processType = process.GetType();
foreach (CartoProcessParameter parameter in template.Parameters)
{
PropertyInfo propInfo = processType.GetProperty(parameter.Name);
if (propInfo == null)
{
_msg.WarnFormat("GdbProcess '{0}' has no property '{1}'",
processType.Name, parameter.Name);
continue;
}
// Parse numbers using invariant culture!
CultureInfo invariant = CultureInfo.InvariantCulture;
Type propertyType = propInfo.PropertyType;
if (propertyType == typeof(bool))
{
bool value = GetBoolean(parameter);
propInfo.SetValue(process, value, null);
}
else if (propertyType == typeof(int))
{
int value = GetInt32(parameter, invariant);
propInfo.SetValue(process, value, null);
}
else if (propertyType == typeof(double))
{
double value = GetDouble(parameter, invariant);
propInfo.SetValue(process, value, null);
}
else if (propertyType == typeof(string))
{
propInfo.SetValue(process, parameter.Value, null);
}
else if (typeof(Enum).IsAssignableFrom(propertyType))
{
object value = GetEnumValue(parameter, propertyType);
propInfo.SetValue(process, value, null);
}
else if (propertyType == typeof(ProcessDatasetName))
{
ProcessDatasetName value = GetProcessDatasetName(parameter, template.Model);
propInfo.SetValue(process, value, null);
}
// TODO Handle other types!
}
return process;
}
[NotNull]
public static IGroupGdbProcess CreateGroupGdbProcess(
[NotNull] CartoProcessGroup template,
[NotNull] DdxModel model,
[NotNull] IList<IGdbProcess> processList)
{
Assert.ArgumentNotNull(template, nameof(template));
Assert.ArgumentNotNull(model, nameof(model));
Assert.ArgumentNotNull(processList, nameof(processList));
ClassDescriptor classDescriptor =
template.AssociatedGroupProcessType.CartoProcessClassDescriptor;
Type t = classDescriptor.GetInstanceType();
Type groupGdbType = typeof(IGroupGdbProcess);
bool isGroupGdbProcess = groupGdbType.IsAssignableFrom(t);
Assert.True(isGroupGdbProcess,
"ClassDescriptor {0} is not for a IGroupGdbProcess",
classDescriptor);
var ctorArgTypes = new[] {typeof(IList<IGdbProcess>)};
ConstructorInfo ctor = t.GetConstructor(ctorArgTypes);
Assert.True(ctor != null && ctor.IsPublic,
"Group GdbProcess must provide a public constructor with signature (IList<IGdbProcess>)");
var process = (IGroupGdbProcess) Activator.CreateInstance(t, processList);
process.Name = template.Name;
process.Description = template.Description;
return process;
}
public static void WriteProcessReport(
[NotNull] IList<CartoProcessType> cartoProcessTypes,
[NotNull] string htmlFileName)
{
Assert.ArgumentNotNull(cartoProcessTypes, nameof(cartoProcessTypes));
Assert.ArgumentNotNullOrEmpty(htmlFileName, nameof(htmlFileName));
using (Stream stream = new FileStream(htmlFileName, FileMode.Create))
{
IProcessReportBuilder builder =
new HtmlProcessReportBuilder("Registered Process Types");
builder.IncludeObsolete = true;
builder.IncludeAssemblyInfo = true;
foreach (CartoProcessType cartoProcessType in cartoProcessTypes)
{
Type processType =
cartoProcessType.CartoProcessClassDescriptor.GetInstanceType();
string name = cartoProcessType.Name;
string description = cartoProcessType.Description;
builder.AddProcessType(processType, name, description);
}
builder.WriteReport(stream);
}
}
#region Private utils
private static bool GetBoolean(CartoProcessParameter parameter)
{
if (bool.TryParse(parameter.Value, out var value))
{
return value;
}
throw new InvalidConfigurationException(
$"Value \"{parameter.Value}\" is not valid for parameter {parameter.Name}");
}
private static int GetInt32(CartoProcessParameter parameter, CultureInfo culture)
{
if (int.TryParse(parameter.Value, NumberStyles.Integer, culture, out var value))
{
return value;
}
throw new InvalidConfigurationException(
$"Value \"{parameter.Value}\" is not valid for parameter {parameter.Name}");
}
private static double GetDouble(CartoProcessParameter parameter, CultureInfo culture)
{
if (double.TryParse(parameter.Value, NumberStyles.Float, culture, out var value))
{
return value;
}
throw new InvalidConfigurationException(
$"Value \"{parameter.Value}\" is not valid for parameter {parameter.Name}");
}
private static object GetEnumValue(CartoProcessParameter parameter, Type enumType)
{
try
{
const bool ignoreCase = true;
return Enum.Parse(enumType, parameter.Value, ignoreCase);
}
catch (Exception ex)
{
throw new InvalidConfigurationException(
$"Value \"{parameter.Value}\" is not valid for parameter {parameter.Name}", ex);
}
}
private static ProcessDatasetName GetProcessDatasetName(
CartoProcessParameter parameter, DdxModel model)
{
// TODO Presently, we cannot distinguish between optional and required parameters
if (string.IsNullOrEmpty(parameter.Value))
{
return null;
}
var dataset = ProcessDatasetName.TryCreate(model, parameter.Value, out var message);
if (dataset == null)
{
throw new InvalidConfigurationException(
$"Parameter {parameter.Name} is invalid: {message}");
}
return dataset;
}
#endregion
}
}
| 29.911017 | 105 | 0.728573 | [
"MIT"
] | ProSuite/ProSuite | src/ProSuite.DomainModel.AO/Processing/CartoProcessUtils.cs | 7,059 | C# |
using System;
using System.IO;
namespace PokemonSaves
{
public class TrainerId : IBinaryParsable
{
private long _startOffset;
private ushort _publicID;
private ushort _secretID;
public long StartOffset { get => _startOffset; set => _startOffset = value; }
public ushort PublicID { get => _publicID; set => _publicID = value; }
public ushort SecretID { get => _secretID; set => _secretID = value; }
public enum Offsets : long
{
PublicID = 0x0000,
SecretID = 0x0002
}
protected void ReadPublicID(BinaryReader binaryReader, long startOffset, GameIDs gameID)
{
binaryReader.BaseStream.Seek(startOffset + (long)Offsets.PublicID, SeekOrigin.Begin);
PublicID = binaryReader.ReadUInt16();
}
protected void ReadSecretID(BinaryReader binaryReader, long startOffset, GameIDs gameID)
{
binaryReader.BaseStream.Seek(startOffset + (long)Offsets.SecretID, SeekOrigin.Begin);
SecretID = binaryReader.ReadUInt16();
}
public void ReadFromBinary(BinaryReader binaryReader, GameIDs gameID)
{
StartOffset = binaryReader.BaseStream.Position;
ReadPublicID(binaryReader, StartOffset, gameID); // PublicID
ReadSecretID(binaryReader, StartOffset, gameID); // SecretID
}
// Write functions:
protected void WritePublicID(BinaryWriter binaryWriter, long startOffset)
{
binaryWriter.BaseStream.Seek(startOffset + (long)Offsets.PublicID, SeekOrigin.Begin);
binaryWriter.Write(PublicID);
}
protected void WriteSecretID(BinaryWriter binaryWriter, long startOffset)
{
binaryWriter.BaseStream.Seek(startOffset + (long)Offsets.SecretID, SeekOrigin.Begin);
binaryWriter.Write(SecretID);
}
public void WriteToBinary(BinaryWriter binaryWriter)
{
WritePublicID(binaryWriter, StartOffset); // PublicID
WriteSecretID(binaryWriter, StartOffset); // SecretID
}
}
} | 35.75 | 97 | 0.641958 | [
"MIT"
] | Jynsaillar/PokemonSavegameEditorCLI | SectionDataTypes/TrainerInfo/TrainerId.cs | 2,145 | C# |
using System;
using System.Reflection;
using System.Linq;
using Harmony;
using Multiplayer.API;
using Verse;
namespace Multiplayer.Compat
{
/// <summary>Path Avoid by Kiame Vivacity</summary>
/// <remarks>Everything works</remarks>
/// <see href="https://steamcommunity.com/sharedfiles/filedetails/?id=1180719857"/>
/// <see href="https://github.com/KiameV/rimworld-pathavoid"/>
[MpCompatFor("[KV] Path Avoid - 1.0")]
public class PathAvoidCompat
{
static Type PathAvoidDefType;
static Type Designator_PathAvoidType;
static FieldInfo PathAvoidDefField;
public PathAvoidCompat(ModContentPack mod)
{
PathAvoidDefType = AccessTools.TypeByName("PathAvoid.PathAvoidDef");
Designator_PathAvoidType = AccessTools.TypeByName("PathAvoid.Designator_PathAvoid");
PathAvoidDefField = AccessTools.Field(Designator_PathAvoidType, "def");
MP.RegisterSyncWorker<Designator>(PathAvoidDesignatorSyncWorker, Designator_PathAvoidType);
}
static void PathAvoidDesignatorSyncWorker(SyncWorker sw, ref Designator designator)
{
Def def = null;
if (sw.isWriting) {
def = (Def) PathAvoidDefField.GetValue(designator);
sw.Write(def.defName);
} else {
string defName = sw.Read<string>();
def = GenDefDatabase.GetDef(PathAvoidDefType, defName, false);
Log.Message($"R Def: {def}");
designator = (Designator) Activator.CreateInstance(Designator_PathAvoidType, new object[] { def });
}
}
}
}
| 34 | 115 | 0.644658 | [
"MIT"
] | cvanderjagt/Multiplayer-Compatibility | Source/Mods/PathAvoid.cs | 1,668 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class ManagePublicationFrequencies {
/// <summary>
/// Master property.
/// </summary>
/// <remarks>
/// Auto-generated property.
/// </remarks>
public new MediaRelationsSiteApp.DataManagement.Manage Master {
get {
return ((MediaRelationsSiteApp.DataManagement.Manage)(base.Master));
}
}
}
| 28.153846 | 81 | 0.484973 | [
"Apache-2.0"
] | AlessiaYChen/gcpe-hub | Hub.Legacy/Gcpe.Hub.Legacy.Website/Contacts/DataManagement/ManagePublicationFrequencies.aspx.designer.cs | 734 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generated from: ItemAddedEventResponse.proto
// Note: requires additional types generated from: EventId.proto
namespace Alachisoft.NCache.Common.Protobuf
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ItemAddedEventResponse")]
public partial class ItemAddedEventResponse : global::ProtoBuf.IExtensible
{
public ItemAddedEventResponse() {}
private string _key = "";
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"key", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string key
{
get { return _key; }
set { _key = value; }
}
private Alachisoft.NCache.Common.Protobuf.EventId _eventId = null;
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"eventId", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(null)]
public Alachisoft.NCache.Common.Protobuf.EventId eventId
{
get { return _eventId; }
set { _eventId = value; }
}
private int _flag = default(int);
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"flag", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int flag
{
get { return _flag; }
set { _flag = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
| 38.673077 | 128 | 0.652412 | [
"Apache-2.0"
] | Alachisoft/NCache | Src/NCCommon/Protobuf/ItemAddedEventResponse.cs | 2,011 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aiven.Outputs
{
[OutputType]
public sealed class OpenSearchComponent
{
public readonly string? Component;
public readonly string? Host;
public readonly string? KafkaAuthenticationMethod;
public readonly int? Port;
public readonly string? Route;
public readonly bool? Ssl;
public readonly string? Usage;
[OutputConstructor]
private OpenSearchComponent(
string? component,
string? host,
string? kafkaAuthenticationMethod,
int? port,
string? route,
bool? ssl,
string? usage)
{
Component = component;
Host = host;
KafkaAuthenticationMethod = kafkaAuthenticationMethod;
Port = port;
Route = route;
Ssl = ssl;
Usage = usage;
}
}
}
| 24.74 | 88 | 0.602264 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-aiven | sdk/dotnet/Outputs/OpenSearchComponent.cs | 1,237 | C# |
using Library.Constants;
using Microsoft.Extensions.DependencyInjection;
namespace Library.ApiFramework.Authorization
{
public static class AuthorizationServiceCollectionExtension
{
public static IServiceCollection ConfigurePermissions(this IServiceCollection services)
{
services.AddAuthorization(opts => opts.AddPolicy(PermissionGroup.AdminLibrary, policy => policy.RequireClaim("Permission", PermissionGroup.AdminLibrary)));
return services;
}
}
}
| 32.125 | 167 | 0.747082 | [
"MIT"
] | hoangphuong020193/library | back-end/Library/LibraryApiFramework/Authorization/AuthorizationServiceCollectionExtension.cs | 516 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Aliencube.FeedSchemata.Rss.Rss10")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Aliencube.FeedSchemata.Rss.Rss10")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a2847e5d-0aa8-4390-ae16-971860e0ea76")]
| 43.85 | 84 | 0.785633 | [
"MIT"
] | aliencube/Feed-Schemata | SourceCodes/RSS/RssSchema.1.0/Properties/AssemblyInfo.cs | 879 | C# |
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection;
using SelfDC.Utils;
using System.IO;
using System.Drawing;
namespace SelfDC.Views
{
public partial class MainMenu : Form
{
private OrderForm oForm;
private LabelsForm lForm;
private InventoryForm iForm;
public MainMenu()
{
ScsUtils.WriteLog("Creazione maschera " + this.Name);
InitializeComponent();
oForm = new OrderForm();
lForm = new LabelsForm();
iForm = new InventoryForm();
}
/** visualizza le info sul programma */
private void actAbout(object sender, EventArgs e)
{
string ProductName = Assembly.GetExecutingAssembly().FullName;
ScsUtils.WriteLog("Apertura info applicazione");
MessageBox.Show(
ProductName + "\nDesigned by Maurizio Aru"
, "Info"
, MessageBoxButtons.OK
, MessageBoxIcon.Asterisk
,MessageBoxDefaultButton.Button1);
}
private void actQuit(object sender, EventArgs e)
{
ScsUtils.WriteLog("Richiesta di chiusura dell'applicazione da " + this.GetType().ToString());
Close();
}
private void MainMenu_Closing(object sender, CancelEventArgs e)
{
DialogResult res = DialogResult.No;
res = MessageBox.Show("Stai per chiudere l'applicazione?\nTutte le raccolte andranno perse\nContinuare?",
"Chiusura Applicazione", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
if (res == DialogResult.No) e.Cancel = true;
if (e.Cancel)
ScsUtils.WriteLog("Chiusura annullata dall'utente");
else
{
ScsUtils.WriteLog("Chiusura confermata dall'utente");
}
}
private void actNewOrder(object sender, EventArgs e)
{
ScsUtils.WriteLog(string.Format("Richiesta apertura della maschera {0}", oForm.Name));
oForm.Show();
}
private void actNewLabel(object sender, EventArgs e)
{
ScsUtils.WriteLog(string.Format("Richiesta apertura della maschera {0}", lForm.Name));
lForm.Show();
}
private void actNewInventory(object sender, EventArgs e)
{
ScsUtils.WriteLog(string.Format("Richiesta apertura della maschera {0}", iForm.Name));
iForm.Show();
}
private void MainMenu_Resize(object sender, EventArgs e)
{
// definisco una matrice di pulsanti 3x3
int numCols = 3;
int numRows = 3;
int borderSize = 3;
// Ridimensiona i pulsanti in modo che stiano sempre in 3 colonne
// calcola la dimensione minima
int tableSize = this.ClientSize.Width > this.ClientSize.Height ? this.ClientSize.Height : this.ClientSize.Width;
// calcolo la dimensione dei pulsanti in base alla grandezza della finestra
// Pulsanti quadrati: H = W
int btnWidth = tableSize / numCols;
int btnHeight = btnWidth;
/*
for (int i = 0; i < numCols; i++) // colonne
{
for (int j = 0; j < numRows; j++) // righe
{
// è uno dei pulsanti del menu
string ctrlName = string.Format("picButton{0}{1}", i, j);
PictureBox ctrl = this.Controls.Find(ctlrName) ;
ctrl.Height = btnHeight - (2 * borderSize);
ctrl.Width = btnWidth - (2 * borderSize);
}
}
*/
// colonna 1
picButton11.Top = borderSize;
picButton11.Left = borderSize;
picButton11.Width = btnWidth - (2 * borderSize);
picButton11.Height = btnHeight - (2 * borderSize);
picButton12.Top = borderSize;
picButton12.Left = btnWidth + borderSize;
picButton12.Width = btnWidth - (2 * borderSize);
picButton12.Height = btnHeight - (2 * borderSize);
picButton13.Top = borderSize;
picButton13.Left = (2 * btnWidth) + borderSize;
picButton13.Width = btnWidth - (2 * borderSize);
picButton13.Height = btnHeight - (2 * borderSize);
// colonna 2
picButton21.Top = borderSize;
picButton21.Left = borderSize;
picButton21.Width = btnWidth - (2 * borderSize);
picButton21.Height = btnHeight - (2 * borderSize);
picButton22.Top = borderSize;
picButton22.Left = btnWidth + borderSize;
picButton22.Width = btnWidth - (2 * borderSize);
picButton22.Height = btnHeight - (2 * borderSize);
picButton23.Top = borderSize;
picButton23.Left = (2 * btnWidth) + borderSize;
picButton23.Width = btnWidth - (2 * borderSize);
picButton23.Height = btnHeight - (2 * borderSize);
}
private void MainMenu_Load(object sender, EventArgs e)
{
ScsUtils.WriteLog("Caricamento maschera " + this.Name);
string logoFileName = ScsUtils.GetAppPath() + Path.DirectorySeparatorChar + "app.png";
if (File.Exists(logoFileName))
{
picLogo.Image = new Bitmap(logoFileName);
}
// riporta le info di versione nel box in alto a destra
lblAppName.Text = Assembly.GetExecutingAssembly().GetName().Name.ToString();
lblAppVersion.Text = string.Format("v. {0}", Assembly.GetExecutingAssembly().GetName().Version.ToString());
}
private void MainMenu_Closed(object sender, EventArgs e)
{
// In chiusura salvo la configurazione
Settings.SaveToFile(Settings.AppCfgFileName);
}
}
} | 36.920732 | 124 | 0.568456 | [
"Apache-2.0"
] | ginopc/SelfDC | Views/MainMenu.cs | 6,058 | C# |
using MediatR;
using System;
using Microsoft.Extensions.Logging;
using AutoMapper;
using CoinTrackApi.Application.Interfaces;
using System.Threading;
using System.Threading.Tasks;
using CoinTrackApi.Application.Dto;
using CoinTrackApi.Core;
namespace CoinTrackApi.Application.Commands
{
public class GetCoinPriceCommand : IRequest<CommandResult<CoinPriceDto>>
{
public GetCoinPriceCommand(string symbol)
{
Symbol = symbol;
}
public string Symbol { get; }
}
public class GetCoinPriceCommandHandler : IRequestHandler<GetCoinPriceCommand,
CommandResult<CoinPriceDto>>
{
private readonly ILogger<GetCoinPriceCommandHandler> _logger;
private readonly IMapper _mapper;
private readonly ICoinService _coinService;
private readonly ICoinRepository _coinRepository;
public GetCoinPriceCommandHandler(IMapper mapper,
ILogger<GetCoinPriceCommandHandler> logger, ICoinService coinService, ICoinRepository coinRepository)
{
_mapper = mapper;
_logger = logger;
_coinService = coinService;
_coinRepository = coinRepository;
}
public async Task<CommandResult<CoinPriceDto>> Handle(GetCoinPriceCommand request,
CancellationToken cancellationToken)
{
try
{
var coin = await _coinRepository.Get(request.Symbol);
if (coin is null)
{
throw new Exception(Resource.FailedToRetrieveCoin);
}
var coinPrice = await _coinService.GetCoinPrice(coin.Symbol);
var coinPriceDto = _mapper.Map<CoinPriceDto>(coinPrice);
return new CommandResult<CoinPriceDto>(coinPriceDto);
}
catch (Exception e)
{
var failureReason = Resource.FailedToRetrieveCoinPrice;
_logger.LogError(e, failureReason);
return new CommandResult<CoinPriceDto>(failureReason);
}
}
}
} | 32.90625 | 113 | 0.639601 | [
"MIT"
] | stackpond/cointrack-api | CoinTrackApi.Core/Commands/GetCoinPriceCommand.cs | 2,108 | C# |
/*
* Copyright 2010-2014 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 greengrass-2017-06-07.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Greengrass.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Greengrass.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ResourceDataContainer Object
/// </summary>
public class ResourceDataContainerUnmarshaller : IUnmarshaller<ResourceDataContainer, XmlUnmarshallerContext>, IUnmarshaller<ResourceDataContainer, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
ResourceDataContainer IUnmarshaller<ResourceDataContainer, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ResourceDataContainer Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
ResourceDataContainer unmarshalledObject = new ResourceDataContainer();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("LocalDeviceResourceData", targetDepth))
{
var unmarshaller = LocalDeviceResourceDataUnmarshaller.Instance;
unmarshalledObject.LocalDeviceResourceData = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("LocalVolumeResourceData", targetDepth))
{
var unmarshaller = LocalVolumeResourceDataUnmarshaller.Instance;
unmarshalledObject.LocalVolumeResourceData = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("S3MachineLearningModelResourceData", targetDepth))
{
var unmarshaller = S3MachineLearningModelResourceDataUnmarshaller.Instance;
unmarshalledObject.S3MachineLearningModelResourceData = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SageMakerMachineLearningModelResourceData", targetDepth))
{
var unmarshaller = SageMakerMachineLearningModelResourceDataUnmarshaller.Instance;
unmarshalledObject.SageMakerMachineLearningModelResourceData = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SecretsManagerSecretResourceData", targetDepth))
{
var unmarshaller = SecretsManagerSecretResourceDataUnmarshaller.Instance;
unmarshalledObject.SecretsManagerSecretResourceData = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static ResourceDataContainerUnmarshaller _instance = new ResourceDataContainerUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ResourceDataContainerUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.25 | 176 | 0.641679 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Greengrass/Generated/Model/Internal/MarshallTransformations/ResourceDataContainerUnmarshaller.cs | 4,669 | C# |
// Copyright (c) 2022 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System.Diagnostics.CodeAnalysis;
using ReactiveUI.Fody.Helpers;
using Xunit;
namespace ReactiveUI.Fody.Tests.API;
/// <summary>
/// Tests for checking if the Fody public API is not changing.
/// We have a file checked into the repository with the approved public API.
/// If it is changing you'll need to override to make it obvious the API has changed
/// for version changing reasons.
/// </summary>
[ExcludeFromCodeCoverage]
public class ApiApprovalTests : ApiApprovalBase
{
/// <summary>
/// Checks the version API.
/// </summary>
[Fact]
public void ReactiveUIFody() => CheckApproval(typeof(ReactiveAttribute).Assembly);
} | 33.785714 | 86 | 0.742072 | [
"MIT"
] | Awsmolak/ReactiveUI | src/ReactiveUI.Fody.Tests/API/ApiApprovalTests.cs | 948 | C# |
#pragma checksum "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "bf56a01b7dfc73e3f8a01dfbb4664532f1d615cc"
// <auto-generated/>
#pragma warning disable 1591
namespace Blazor_FrontEnd.Pages
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Microsoft.AspNetCore.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Microsoft.AspNetCore.Components.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Microsoft.AspNetCore.Components.Web.Virtualization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Blazor_FrontEnd;
#line default
#line hidden
#nullable disable
#nullable restore
#line 10 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\_Imports.razor"
using Blazor_FrontEnd.Shared;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
using Blazor_FrontEnd.Data;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
using Blazor_FrontEnd.Data.RequestCodes;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
using System.Threading;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
using NetMQ;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
using NetMQ.Sockets;
#line default
#line hidden
#nullable disable
[Microsoft.AspNetCore.Components.RouteAttribute("/Forklift")]
public partial class ForkLift : Microsoft.AspNetCore.Components.ComponentBase, IDisposable
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
__builder.AddMarkupContent(0, "<h1>Heftruck status</h1>\r\n<hr>\r\n<br>\r\n");
__builder.AddMarkupContent(1, "<h3>Batterijniveau</h3> \r\n");
__builder.OpenElement(2, "label");
__builder.AddAttribute(3, "for", "batteryGauge");
__builder.AddContent(4, "Resterende lading ( ");
#nullable restore
#line 15 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
__builder.AddContent(5, percentage);
#line default
#line hidden
#nullable disable
__builder.AddContent(6, " %): ");
__builder.CloseElement();
__builder.AddMarkupContent(7, "\r\n");
__builder.OpenElement(8, "meter");
__builder.AddAttribute(9, "style", "width:80%;");
__builder.AddAttribute(10, "id", "batteryGauge");
__builder.AddAttribute(11, "min", "0");
__builder.AddAttribute(12, "max", "100");
__builder.AddAttribute(13, "value",
#nullable restore
#line 16 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
(int?)(percentage)
#line default
#line hidden
#nullable disable
);
__builder.CloseElement();
__builder.AddMarkupContent(14, "\r\n<hr>\r\n");
__builder.AddMarkupContent(15, "<h3>Handrem</h3>\r\n<br>");
#nullable restore
#line 20 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
if (handbrakeActivated)
{
#line default
#line hidden
#nullable disable
__builder.AddMarkupContent(16, "<p style=\"color:forestgreen\">Handrem geactiveerd</p>");
#nullable restore
#line 23 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
} else
{
#line default
#line hidden
#nullable disable
__builder.AddMarkupContent(17, "<p style=\"color:firebrick\">Handrem gedeactiveerd</p>");
#nullable restore
#line 26 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
}
#line default
#line hidden
#nullable disable
__builder.AddMarkupContent(18, "<br>\r\n");
__builder.AddMarkupContent(19, "<label for=\"handbrakeToggle\">Handrem: </label>\r\n");
__builder.OpenElement(20, "input");
__builder.AddAttribute(21, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this,
#nullable restore
#line 30 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
ToggleHandbrake
#line default
#line hidden
#nullable disable
));
__builder.AddAttribute(22, "type", "checkbox");
__builder.AddAttribute(23, "data-toggle", "toggle");
__builder.AddAttribute(24, "data-on", "aan");
__builder.AddAttribute(25, "data-off", "uit");
__builder.AddAttribute(26, "data-onstyle", "success");
__builder.AddAttribute(27, "data-offstyle", "danger");
__builder.AddAttribute(28, "checked", Microsoft.AspNetCore.Components.BindConverter.FormatValue(
#nullable restore
#line 30 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
handbrakeActivated
#line default
#line hidden
#nullable disable
));
__builder.AddAttribute(29, "onchange", Microsoft.AspNetCore.Components.EventCallback.Factory.CreateBinder(this, __value => handbrakeActivated = __value, handbrakeActivated));
__builder.SetUpdatesAttributeName("checked");
__builder.CloseElement();
__builder.AddMarkupContent(30, "\r\n<hr>");
}
#pragma warning restore 1998
#nullable restore
#line 35 "C:\Users\arthu\Documents\Rider Projects\gip rpi\frontend\Blazor_FrontEnd\Pages\ForkLift.razor"
private float? percentage = null;
private bool handbrakeActivated = false;
private string? handbrakeStatus = null;
private string? batteryPercentage = null;
private CancellationTokenSource cancelSource;
private RequestSocket client = new RequestSocket();
private void ToggleHandbrake()
{
using(var client = new RequestSocket())
{
client.Connect("tcp://localhost:2100");
if (handbrakeActivated)
{
client.SendFrame(new byte[] { Convert.ToByte(RequestCodes.SetHandbrakeOff) });
client.ReceiveFrameBytes();
handbrakeActivated = false;
} else
{
client.SendFrame(new byte[] { Convert.ToByte(RequestCodes.SetHandbrakeOn) });
client.ReceiveFrameBytes();
handbrakeActivated = false;
}
}
}
protected override async Task OnInitializedAsync()
{
cancelSource = new CancellationTokenSource();
using(var client = new RequestSocket())
{
await base.OnInitializedAsync();
client.Connect("tcp://localhost:2100");
client.SendFrame(new byte[] {Convert.ToByte(RequestCodes.GetHandbrakeStatus)});
var response = client.ReceiveFrameString();
handbrakeActivated = bool.Parse(response);
client.SendFrame(new byte[] {Convert.ToByte(RequestCodes.GetBatteryPercentage)});
var response2 = client.ReceiveFrameString();
Console.WriteLine(response2);
percentage = (float.Parse(response2)/ 10000.0F)*100.0F;
}
/*
cancelSource = new CancellationTokenSource();
try
{
handbrakeStatus = await backendComm.SendCode(RequestCodes.GetHandbrakeStatus, cancelSource.Token).ConfigureAwait(false);
batteryPercentage = await backendComm.SendCode(RequestCodes.GetBatteryPercentage, cancelSource.Token).ConfigureAwait(false);
await base.OnInitializedAsync().ConfigureAwait(false);
}
catch (TaskCanceledException)
{
Console.WriteLine("canceled on forklift page");
}
*/
}
public void Dispose()
{
cancelSource.Cancel();
cancelSource.Dispose();
}
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Components.InjectAttribute] private IPCClient backendComm { get; set; }
}
}
#pragma warning restore 1591
| 36.21875 | 196 | 0.697728 | [
"MIT"
] | DeepBlue-Dev/Gip-rpi-software | frontend/Blazor_FrontEnd/obj/Debug/net5.0/Razor/Pages/ForkLift.razor.g.cs | 10,431 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Plotter : MonoBehaviour
{
private readonly List<decimal> expectedValues = new List<decimal>()
{
0.25686095751884m,
-0.89310642318349m,
-0.36930118517397m
};
private List<Sv> coords;
private readonly List<decimal> v = new List<decimal>()
{
0.18983879552606m, // 0
0.20847820715387m, // 1
0.3373248250886m, // 2
0.39831700267993m, // 3
0.6444904486331m, // 4
0.73564182776852m, // 5
0.85296865578697m, // 6
0.9818152737217m, // 7
};
public Plotter()
{
coords = new List<Sv>()
{
new Sv(v[4], -v[1], v[5]),
new Sv(-v[6], -v[2], v[3]),
new Sv(v[2], v[3], -v[6]),
new Sv(-v[0], -v[7], 0), // eindigt op 0
new Sv(v[1], -v[5], v[4]),
new Sv(v[6], v[2], v[3]),
new Sv(v[5], v[4], -v[1]),
new Sv(v[0], -v[7], 0), //begint bij 0
new Sv(v[7], 0, -v[0]),
new Sv(-v[7], 0, -v[0]),
new Sv(v[6], v[2], -v[3]), //Eerste zonder 0
new Sv(v[6], -v[2], v[3]),
new Sv(-v[1], -v[5], -v[4]),
new Sv(v[3], -v[6], v[2]),
new Sv(-v[2], -v[3], v[6])
};
}
public GameObject prefabje;
public GameObject prefabjeFoen;
public GameObject prefabLijn;
// Start is called before the first frame update
void Start()
{
var mul = 10.0f;
var dfoen = new Sv(expectedValues[0], expectedValues[1], expectedValues[2]);
DrawBol(Vector3.zero, dfoen.ToVector3() * mul, prefabjeFoen, Color.red);
foreach (var value in coords)
{
DrawBol(Vector3.zero, value.ToVector3() * mul, prefabje, Color.blue);
}
}
private void DrawBol(Vector3 from, Vector3 to, GameObject prefab, Color lineColor)
{
var ga = GameObject.Instantiate(prefab);
ga.transform.SetParent(this.transform, true);
ga.transform.localPosition = to;
DrawLine(from, to, lineColor, 10000f);
}
void DrawLine(Vector3 start, Vector3 end, Color color, float duration = 0.2f)
{
GameObject myLine = GameObject.Instantiate(prefabLijn);
myLine.transform.position = start;
LineRenderer lr = myLine.GetComponent<LineRenderer>();
//lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
lr.startColor = color;
lr.endColor = color;
lr.startWidth = 0.1f;
lr.endWidth = 0.1f;
lr.SetPosition(0, start);
lr.SetPosition(1, end);
GameObject.Destroy(myLine, duration);
}
// Update is called once per frame
void Update()
{
}
}
| 27.911765 | 89 | 0.539164 | [
"MIT"
] | devedse/FactorioSpaceExplorationDeducer | FactorioDeducerUnityPlotter/Assets/Plotter.cs | 2,849 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNative.RecoveryServices.Latest.Inputs
{
/// <summary>
/// InMageRcm disk input.
/// </summary>
public sealed class InMageRcmDiskInputArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The disk encryption set ARM Id.
/// </summary>
[Input("diskEncryptionSetId")]
public Input<string>? DiskEncryptionSetId { get; set; }
/// <summary>
/// The disk Id.
/// </summary>
[Input("diskId")]
public Input<string>? DiskId { get; set; }
/// <summary>
/// The disk type.
/// </summary>
[Input("diskType")]
public InputUnion<string, Pulumi.AzureNative.RecoveryServices.Latest.DiskAccountType>? DiskType { get; set; }
/// <summary>
/// The log storage account ARM Id.
/// </summary>
[Input("logStorageAccountId")]
public Input<string>? LogStorageAccountId { get; set; }
public InMageRcmDiskInputArgs()
{
}
}
}
| 28.191489 | 117 | 0.601509 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/RecoveryServices/Latest/Inputs/InMageRcmDiskInputArgs.cs | 1,325 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("IoT.Server.Host")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IoT.Server.Host")]
[assembly: AssemblyCopyright("Copyright © Paramesh Gunasekaran 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("869a5c89-9e94-4c4c-8b4e-3b771cbb4a8b")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 37.866667 | 70 | 0.762324 | [
"MIT"
] | parameshg/orleans-prototype | IoT.Server.Host/Properties/AssemblyInfo.cs | 571 | C# |
namespace Lykke.Job.NeoClaimTransactionsExecutor.Services
{
public class ClaimGasStarterSettings
{
public ClaimGasStarterSettings(string neoAssetId,
string gasAssetId,
string claimTriggerCronExpression,
string neoHotWalletAddress)
{
NeoAssetId = neoAssetId;
GasAssetId = gasAssetId;
ClaimTriggerCronExpression = claimTriggerCronExpression;
NeoHotWalletAddress = neoHotWalletAddress;
}
public string NeoAssetId { get; }
public string GasAssetId { get; }
public string ClaimTriggerCronExpression { get; }
public string NeoHotWalletAddress { get; }
}
}
| 28.4 | 68 | 0.647887 | [
"MIT"
] | LykkeCity/Lykke.Job.NeoClaimTransactionsExecutor | src/Lykke.Job.NeoClaimTransactionsExecutor/Services/ClaimGasStarterSettings.cs | 712 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Compute.Tests
{
public class ExtensionTests : VMTestBase
{
VirtualMachineExtension GetTestVMExtension()
{
var vmExtension = new VirtualMachineExtension
{
Location = ComputeManagementTestUtilities.DefaultLocation,
Tags = new Dictionary<string, string>() { { "extensionTag1", "1" }, { "extensionTag2", "2" } },
Publisher = "Microsoft.Compute",
VirtualMachineExtensionType = "VMAccessAgent",
TypeHandlerVersion = "2.0",
AutoUpgradeMinorVersion = false,
ForceUpdateTag = "RerunExtension",
Settings = "{}",
ProtectedSettings = "{}",
EnableAutomaticUpgrade = false,
};
typeof(ResourceWithOptionalLocation).GetRuntimeProperty("Name").SetValue(vmExtension, "vmext01");
typeof(ResourceWithOptionalLocation).GetRuntimeProperty("Type").SetValue(vmExtension, "Microsoft.Compute/virtualMachines/extensions");
return vmExtension;
}
VirtualMachineExtensionUpdate GetTestVMUpdateExtension()
{
var vmExtensionUpdate = new VirtualMachineExtensionUpdate
{
Tags =
new Dictionary<string, string>
{
{ "extensionTag1", "1" },
{ "extensionTag2", "2" },
{ "extensionTag3", "3" }
},
SuppressFailures = true
};
return vmExtensionUpdate;
}
[Fact]
public void TestVMExtensionOperations()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
var rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string asName = ComputeManagementTestUtilities.GenerateName("as");
VirtualMachine inputVM;
try
{
// Create Storage Account, so that both the VMs can share it
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
var vm = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM);
// Delete an extension that does not exist in the VM. A http status code of NoContent should be returned which translates to operation success.
m_CrpClient.VirtualMachineExtensions.Delete(rgName, vm.Name, "VMExtensionDoesNotExist");
// Add an extension to the VM
var vmExtension = GetTestVMExtension();
var response = m_CrpClient.VirtualMachineExtensions.CreateOrUpdate(rgName, vm.Name, vmExtension.Name, vmExtension);
ValidateVMExtension(vmExtension, response);
// Perform a Get operation on the extension
var getVMExtResponse = m_CrpClient.VirtualMachineExtensions.Get(rgName, vm.Name, vmExtension.Name);
ValidateVMExtension(vmExtension, getVMExtResponse);
// Perform a GetExtensions on the VM
var getVMExtsResponse = m_CrpClient.VirtualMachineExtensions.List(rgName, vm.Name);
Assert.True(getVMExtsResponse.Value.Count > 0);
var vme = getVMExtsResponse.Value.Where(c => c.Name == "vmext01");
Assert.Single(vme);
ValidateVMExtension(vmExtension, vme.First());
// Validate Get InstanceView for the extension
var getVMExtInstanceViewResponse = m_CrpClient.VirtualMachineExtensions.Get(rgName, vm.Name, vmExtension.Name, "instanceView");
ValidateVMExtensionInstanceView(getVMExtInstanceViewResponse.InstanceView);
// Update extension on the VM
var vmExtensionUpdate = GetTestVMUpdateExtension();
m_CrpClient.VirtualMachineExtensions.Update(rgName, vm.Name, vmExtension.Name, vmExtensionUpdate);
vmExtension.Tags["extensionTag3"] = "3";
vmExtension.SuppressFailures = true;
getVMExtResponse = m_CrpClient.VirtualMachineExtensions.Get(rgName, vm.Name, vmExtension.Name);
ValidateVMExtension(vmExtension, getVMExtResponse);
// Validate the extension in the VM info
var getVMResponse = m_CrpClient.VirtualMachines.Get(rgName, vm.Name);
// TODO AutoRest: Recording Passed, but these assertions failed in Playback mode
ValidateVMExtension(vmExtension, getVMResponse.Resources.FirstOrDefault(c => c.Name == vmExtension.Name));
// Validate the extension instance view in the VM instance-view
var getVMWithInstanceViewResponse = m_CrpClient.VirtualMachines.Get(rgName, vm.Name, InstanceViewTypes.InstanceView);
ValidateVMExtensionInstanceView(getVMWithInstanceViewResponse.InstanceView.Extensions.FirstOrDefault(c => c.Name == vmExtension.Name));
// Validate the extension delete API
m_CrpClient.VirtualMachineExtensions.Delete(rgName, vm.Name, vmExtension.Name);
// Add another extension to the VM with protectedSettingsFromKeyVault
var vmExtension2 = GetTestVMExtension();
AddProtectedSettingsFromKeyVaultToExtension(vmExtension2);
//For now we just validate that the protectedSettingsFromKeyVault has been accepted and persisted. Since we didn't create a KV, this failure is expected
try
{
response = m_CrpClient.VirtualMachineExtensions.CreateOrUpdate(rgName, vm.Name, vmExtension2.Name, vmExtension2);
}
catch (Exception e)
{
Assert.Contains("either has not been enabled for deployment or the vault id provided", e.Message);
}
}
finally
{
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
private void ValidateVMExtension(VirtualMachineExtension vmExtExpected, VirtualMachineExtension vmExtReturned)
{
Assert.NotNull(vmExtReturned);
Assert.True(!string.IsNullOrEmpty(vmExtReturned.ProvisioningState));
Assert.True(vmExtExpected.Publisher == vmExtReturned.Publisher);
Assert.True(vmExtExpected.VirtualMachineExtensionType == vmExtReturned.VirtualMachineExtensionType);
Assert.True(vmExtExpected.AutoUpgradeMinorVersion == vmExtReturned.AutoUpgradeMinorVersion);
Assert.True(vmExtExpected.TypeHandlerVersion == vmExtReturned.TypeHandlerVersion);
Assert.True(vmExtExpected.Settings.ToString() == vmExtReturned.Settings.ToString());
Assert.True(vmExtExpected.ForceUpdateTag == vmExtReturned.ForceUpdateTag);
Assert.True(vmExtExpected.Tags.SequenceEqual(vmExtReturned.Tags));
Assert.True(vmExtExpected.EnableAutomaticUpgrade == vmExtReturned.EnableAutomaticUpgrade);
Assert.True(vmExtExpected.SuppressFailures == vmExtReturned.SuppressFailures);
}
private void ValidateVMExtensionInstanceView(VirtualMachineExtensionInstanceView vmExtInstanceView)
{
Assert.NotNull(vmExtInstanceView);
Assert.NotNull(vmExtInstanceView.Statuses[0].DisplayStatus);
Assert.NotNull(vmExtInstanceView.Statuses[0].Code);
Assert.NotNull(vmExtInstanceView.Statuses[0].Level);
Assert.NotNull(vmExtInstanceView.Statuses[0].Message);
}
private void AddProtectedSettingsFromKeyVaultToExtension(VirtualMachineExtension vmExtension)
{
vmExtension.ProtectedSettings = null;
//string idValue = string.Format("subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.KeyVault/vaults/kvName", m_subId, resourceGroupName);
string idValue = string.Format("/subscriptions/e37510d7-33b6-4676-886f-ee75bcc01871/resourceGroups/RGforSDKtestResources/providers/Microsoft.KeyVault/vaults/keyVaultInSoutheastAsia");
string sourceVaultId = string.Format("\"id\": \"{0}\"", idValue);
string sourceVault = "{ " + sourceVaultId + " }";
string secret = string.Format("\"secretUrl\": \"{0}\"", "https://keyvaultinsoutheastasia.vault.azure.net/secrets/SecretForTest/2375df95e3da463c81c43c300f6506ab");
vmExtension.ProtectedSettingsFromKeyVault = new JRaw("{ " + string.Format("\"sourceVault\": {0},{1}", sourceVault, secret) + " }");
}
}
}
| 54 | 195 | 0.635113 | [
"MIT"
] | damodaravadhani/azure-sdk-for-net | sdk/compute/Microsoft.Azure.Management.Compute/tests/ScenarioTests/ExtensionTests.cs | 9,666 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WFA_MayinTarlasi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WFA_MayinTarlasi")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("114210ae-ff05-46b2-9d4c-eee84023456c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.810811 | 85 | 0.730501 | [
"MIT"
] | BercKoskun/CSharpBilge | Introduction/Ocak/16.01/WFA_MayinTarlasi/WFA_MayinTarlasi/Properties/AssemblyInfo.cs | 1,439 | C# |
using UnityEditor;
using UnityEngine;
namespace QFramework
{
public partial class EditorUtil
{
/// <summary>
/// 打开所在文件夹
/// </summary>
public static void OpenInFolder(string folderPath)
{
Application.OpenURL("file:///" + folderPath);
}
/// <summary>
/// 导出相应的UnityPackage
/// </summary>
public static void ExportPackage(string assetPathName, string fileName)
{
AssetDatabase.ExportPackage(assetPathName, fileName, ExportPackageOptions.Recurse);
}
/// <summary>
/// 复用MenuItem
/// </summary>
public static void CallMenuItem(string menuPath)
{
EditorApplication.ExecuteMenuItem(menuPath);
}
}
}
| 22.628571 | 95 | 0.566919 | [
"MIT"
] | WzqProgrammer/QFramework | Assets/QFramework/Framework/Util/EditorUtil.cs | 822 | C# |
using System;
using System.Globalization;
using Bunit;
using FluentAssertions;
using NUnit.Framework;
namespace MudBlazor.UnitTests.Components
{
[TestFixture]
public class ProgressLinearTests : BunitTest
{
[Test]
public void DefaultValues()
{
var linear = new MudProgressLinear();
linear.BufferValue.Should().Be(0);
linear.Value.Should().Be(0);
linear.Buffer.Should().BeFalse();
linear.ChildContent.Should().BeNull();
linear.Color.Should().Be(Color.Default);
linear.Indeterminate.Should().BeFalse();
linear.Max.Should().Be(100.0);
linear.Min.Should().Be(0.0);
linear.Rounded.Should().BeFalse();
linear.Size.Should().Be(Size.Small);
linear.Striped.Should().BeFalse();
linear.Value.Should().Be(0.0);
linear.Vertical.Should().BeFalse();
}
[Test]
[TestCase(0, 100, 30, 20, 30.0, 20.0)]
[TestCase(0, 10, 3, 2, 30.0, 20.0)]
[TestCase(0, 10, 0.03, 0.02, 0.3, 0.2)]
[TestCase(-100, 0, -70, -80, 30.0, 20.0)]
[TestCase(0, 200, 30, 20, 15, 10)]
[TestCase(200, 400, 230, 220, 15, 10)]
public void CheckingPercentageAndBufferValue(double min, double max, double value, double buffervalue, double expectedValue, double expectedBufferValue)
{
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Min, min);
x.Add(y => y.Max, max);
x.Add(y => y.Value, value);
x.Add(y => y.BufferValue, buffervalue);
});
comp.Instance.Value.Should().Be(value);
comp.Instance.GetValuePercent().Should().Be(expectedValue);
comp.Instance.BufferValue.Should().Be(buffervalue);
comp.Instance.GetBufferPercent().Should().Be(expectedBufferValue);
}
[Test]
[TestCase(0, 100, -30, -20, 0.0, 0.0)]
[TestCase(0, 100, 30, -20, 30, 0.0)]
[TestCase(0, 100, -30, 20, 0.0, 20)]
[TestCase(0, 100, 130, 120, 100, 100)]
[TestCase(0, 100, 30, 120, 30, 100)]
[TestCase(0, 100, 130, 20, 100, 20)]
[TestCase(0, 0, 30, 20, 0.0, 0.0)]
public void EnsureMaxAndMinConsitency(double min, double max, double value, double buffervalue, double expectedValue, double expectedBufferValue)
{
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Min, min);
x.Add(y => y.Max, max);
x.Add(y => y.Value, value);
x.Add(y => y.BufferValue, buffervalue);
});
comp.Instance.Value.Should().Be(value);
comp.Instance.GetValuePercent().Should().Be(expectedValue);
comp.Instance.BufferValue.Should().Be(buffervalue);
comp.Instance.GetBufferPercent().Should().Be(expectedBufferValue);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void DefaultStructure(bool isVertical)
{
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Min, -500);
x.Add(y => y.Max, 500);
x.Add(y => y.Value, -400);
x.Add(y => y.Class, "my-custom-class");
x.Add(y => y.Vertical, isVertical);
});
Console.WriteLine(comp.Markup);
var container = comp.Find(".my-custom-class");
container.GetAttribute("role").Should().Be("progressbar");
container.ChildElementCount.Should().Be(1);
var barContainer = container.Children[0];
barContainer.ClassList.Should().Contain("mud-progress-linear-bars");
barContainer.ChildElementCount.Should().Be(1);
var barElement = barContainer.Children[0];
barElement.ClassList.Should().Contain("mud-progress-linear-bar");
barElement.GetAttribute("style").Should().Be(
isVertical == true ?
$"transform: translateY(90%);" : $"transform: translateX(-90%);");
}
[Test]
public void IndeterminateStructure()
{
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Min, -500);
x.Add(y => y.Max, 500);
x.Add(y => y.Value, -400);
x.Add(y => y.Class, "my-custom-class");
x.Add(y => y.Indeterminate, true);
});
Console.WriteLine(comp.Markup);
var container = comp.Find(".my-custom-class");
container.GetAttribute("role").Should().Be("progressbar");
container.ChildElementCount.Should().Be(1);
var barContainer = container.Children[0];
barContainer.ClassList.Should().Contain("mud-progress-linear-bars");
barContainer.ChildElementCount.Should().Be(2);
var firstBarElement = barContainer.Children[0];
firstBarElement.ClassList.Should().Contain("mud-progress-linear-bar");
var secondBarElement = barContainer.Children[1];
firstBarElement.ClassList.Should().Contain("mud-progress-linear-bar");
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void BufferStructure(bool isVertical)
{
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Min, -500);
x.Add(y => y.Max, 500);
x.Add(y => y.Value, -400);
x.Add(y => y.BufferValue, -100);
x.Add(y => y.Class, "my-custom-class");
x.Add(y => y.Buffer, true);
x.Add(y => y.Vertical, isVertical);
});
Console.WriteLine(comp.Markup);
var container = comp.Find(".my-custom-class");
container.GetAttribute("role").Should().Be("progressbar");
container.ChildElementCount.Should().Be(1);
var barContainer = container.Children[0];
barContainer.ClassList.Should().Contain("mud-progress-linear-bars");
barContainer.ChildElementCount.Should().Be(3);
var firstBarElement = barContainer.Children[0];
firstBarElement.ClassList.Should().Contain("mud-progress-linear-bar");
var secondBarElement = barContainer.Children[1];
secondBarElement.ClassList.Should().Contain("mud-progress-linear-bar");
secondBarElement.GetAttribute("style").Should().Be(
isVertical == true ?
$"transform: translateY(90%);" : $"transform: translateX(-90%);");
var thirdBarElement = barContainer.Children[2];
thirdBarElement.ClassList.Should().Contain("mud-progress-linear-bar", "last");
thirdBarElement.GetAttribute("style").Should().Be(
isVertical == true ?
$"transform: translateY(60%);" : $"transform: translateX(-60%);");
}
[Test]
public void IndeterminateWithChildContent()
{
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Min, -500);
x.Add(y => y.Max, 500);
x.Add(y => y.Value, -400);
x.Add(y => y.Class, "my-custom-class");
x.Add(y => y.Indeterminate, true);
x.Add(y => y.ChildContent, "<p>my content</p>");
});
Console.WriteLine(comp.Markup);
var container = comp.Find(".my-custom-class");
container.GetAttribute("role").Should().Be("progressbar");
container.ChildElementCount.Should().Be(2);
var contentContainer = container.Children[0];
contentContainer.ClassList.Should().Contain("mud-progress-linear-content");
contentContainer.ChildElementCount.Should().Be(1);
contentContainer.TextContent.Should().Be("my content");
var barContainer = container.Children[1];
barContainer.ClassList.Should().Contain("mud-progress-linear-bars");
barContainer.ChildElementCount.Should().Be(2);
var firstBarElement = barContainer.Children[0];
firstBarElement.ClassList.Should().Contain("mud-progress-linear-bar");
var secondBarElement = barContainer.Children[1];
firstBarElement.ClassList.Should().Contain("mud-progress-linear-bar");
}
[Test]
[TestCase(true)]
[TestCase(true)]
public void TestClassesForRounded(bool rounded)
{
var comp = Context.RenderComponent<MudProgressLinear>(x => x.Add(y => y.Rounded, rounded));
var container = comp.Find(".mud-progress-linear");
if (rounded == true)
{
container.ClassList.Should().Contain("mud-progress-linear-rounded");
}
else
{
container.ClassList.Should().NotContain("mud-progress-linear-rounded");
}
}
[Test]
[TestCase(true)]
[TestCase(true)]
public void TestClassesForStriped(bool striped)
{
var comp = Context.RenderComponent<MudProgressLinear>(x => x.Add(y => y.Striped, striped));
var container = comp.Find(".mud-progress-linear");
if (striped == true)
{
container.ClassList.Should().Contain("mud-progress-linear-striped");
}
else
{
container.ClassList.Should().NotContain("mud-progress-linear-striped");
}
}
[Test]
[TestCase(true)]
[TestCase(true)]
public void TestClassesForIntermediate(bool indeterminate)
{
var comp = Context.RenderComponent<MudProgressLinear>(x => x.Add(y => y.Indeterminate, indeterminate));
var container = comp.Find(".mud-progress-linear");
if (indeterminate == true)
{
container.ClassList.Should().Contain("mud-progress-indeterminate");
}
else
{
container.ClassList.Should().NotContain("mud-progress-indeterminate");
}
}
[Test]
[TestCase(false, false)]
[TestCase(false, true)]
[TestCase(true, false)]
[TestCase(true, true)]
public void TestClassesForBuffer(bool buffer, bool indeterminate)
{
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Indeterminate, indeterminate);
x.Add(y => y.Buffer, buffer);
});
var container = comp.Find(".mud-progress-linear");
if (buffer == true && indeterminate == false)
{
container.ClassList.Should().Contain("mud-progress-linear-buffer");
}
else
{
container.ClassList.Should().NotContain("mud-progress-linear-buffer");
}
}
[Test]
[TestCase(Size.Large,"large")]
[TestCase(Size.Medium, "medium")]
[TestCase(Size.Small, "small")]
public void TestClassesForSize(Size size, string expectedString)
{
var comp = Context.RenderComponent<MudProgressLinear>(x => x.Add(y => y.Size, size));
var container = comp.Find(".mud-progress-linear");
container.ClassList.Should().Contain($"mud-progress-linear-{expectedString}");
}
[Test]
[TestCase(Color.Success, "success")]
[TestCase(Color.Surface, "surface")]
[TestCase(Color.Error, "error")]
public void TestClassesForColor(Color color, string expectedString)
{
var comp = Context.RenderComponent<MudProgressLinear>(x => x.Add(y => y.Color, color));
var container = comp.Find(".mud-progress-linear");
container.ClassList.Should().Contain($"mud-progress-linear-color-{expectedString}");
}
[Test]
[TestCase(true)]
[TestCase(true)]
public void TestClassesForVertical(bool vertical)
{
var comp = Context.RenderComponent<MudProgressLinear>(x => x.Add(y => y.Vertical, vertical));
var container = comp.Find(".mud-progress-linear");
if (vertical == true)
{
container.ClassList.Should().Contain("vertical");
container.ClassList.Should().NotContain("horizontal");
}
else
{
container.ClassList.Should().Contain("horizontal");
container.ClassList.Should().NotContain("vertical");
}
}
[Test]
[TestCase("en-us")]
[TestCase("de-DE")]
[TestCase("he-IL")]
[TestCase("ar-ER")]
public void AriaValuesInDifferentCultures(string cultureString)
{
var culture = new CultureInfo(cultureString, false);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Min, 10.2);
x.Add(y => y.Max, 125.22);
x.Add(y => y.Value, 75.3);
x.Add(y => y.Class, "my-custom-class");
});
Console.WriteLine(comp.Markup);
var container = comp.Find(".my-custom-class");
container.GetAttribute("role").Should().Be("progressbar");
container.GetAttribute("aria-valuenow").Should().Be("75.3");
container.GetAttribute("aria-valuemin").Should().Be("10.2");
container.GetAttribute("aria-valuemax").Should().Be("125.22");
}
}
}
| 35.751269 | 160 | 0.543234 | [
"MIT"
] | 1619digital/MudBlazor | src/MudBlazor.UnitTests/Components/ProgressLinearTests.cs | 14,088 | C# |
/*
* MIT License
*
* Copyright(c) 2017 thrzn41
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Thrzn41.CiscoSpark.Version1.OAuth2
{
/// <summary>
/// Cisco Spark OAuth2 Client for API version 1.
/// </summary>
public class SparkOAuth2Client
{
/// <summary>
/// Spark access token API Path.
/// </summary>
protected static readonly string SPARK_ACCESS_TOKEN_API_PATH = SparkAPIClient.GetAPIPath("access_token");
/// <summary>
/// Spark access token API Uri.
/// </summary>
protected static readonly Uri SPARK_ACCESS_TOKEN_API_URI = new Uri(SPARK_ACCESS_TOKEN_API_PATH);
/// <summary>
/// HttpClient for Spark API.
/// </summary>
protected readonly SparkHttpClient sparkHttpClient;
/// <summary>
/// Client secret.
/// </summary>
private string clientSecret;
/// <summary>
/// Client id.
/// </summary>
private string clientId;
/// <summary>
/// Constuctor of SparkOAuth2Client.
/// </summary>
/// <param name="clientSecret">Client secret key.</param>
/// <param name="clientId">Client id.</param>
internal SparkOAuth2Client(string clientSecret, string clientId)
{
this.sparkHttpClient = new SparkHttpClient(null, SparkAPIClient.SPARK_API_URI_PATTERN);
this.clientId = clientId;
this.clientSecret = clientSecret;
}
/// <summary>
/// Converts OAuth2 result to Spark token result.
/// </summary>
/// <param name="source">Source result.</param>
/// <param name="refreshedAt"><see cref="DateTime"/> when the token refreshed.</param>
/// <returns><see cref="SparkResult{TSparkObject}"/> to get result.</returns>
private static SparkResult<TokenInfo> convert(SparkResult<Oauth2TokenInfo> source, DateTime refreshedAt)
{
var result = new SparkResult<TokenInfo>();
result.IsSuccessStatus = source.IsSuccessStatus;
result.HttpStatusCode = source.HttpStatusCode;
result.RetryAfter = source.RetryAfter;
result.TrackingId = source.TrackingId;
var tokenInfo = new TokenInfo();
var data = source.Data;
if (result.IsSuccessStatus)
{
tokenInfo.RefreshedAt = refreshedAt;
tokenInfo.AccessToken = data.AccessToken;
if(data.ExpiresIn.HasValue)
{
tokenInfo.AccessTokenExpiresIn = TimeSpan.FromSeconds(data.ExpiresIn.Value);
tokenInfo.AccessTokenExpiresAt = refreshedAt + tokenInfo.AccessTokenExpiresIn;
}
tokenInfo.RefreshToken = data.RefreshToken;
if (data.RefreshTokenExpiresIn.HasValue)
{
tokenInfo.RefreshTokenExpiresIn = TimeSpan.FromSeconds(data.RefreshTokenExpiresIn.Value);
tokenInfo.RefreshTokenExpiresAt = refreshedAt + tokenInfo.RefreshTokenExpiresIn;
}
}
if(data.HasExtensionData)
{
tokenInfo.JsonExtensionData = data.JsonExtensionData;
}
tokenInfo.HasValues = data.HasValues;
result.Data = tokenInfo;
return result;
}
/// <summary>
/// Gets token info.
/// </summary>
/// <param name="parameters">Query parameters.</param>
/// <param name="cancellationToken"><see cref="CancellationToken"/> to be used for cancellation.</param>
/// <returns><see cref="SparkResult{TSparkObject}"/> to get result.</returns>
private async Task< SparkResult<TokenInfo> > getTokenInfoAsync(NameValueCollection parameters, CancellationToken? cancellationToken = null)
{
DateTime refreshedAt = DateTime.UtcNow;
var result = await this.sparkHttpClient.RequestFormDataAsync<SparkResult<Oauth2TokenInfo>, Oauth2TokenInfo>(
HttpMethod.Post,
SPARK_ACCESS_TOKEN_API_URI,
null,
parameters,
cancellationToken);
result.IsSuccessStatus = (result.IsSuccessStatus && (result.HttpStatusCode == System.Net.HttpStatusCode.OK));
return convert(result, refreshedAt);
}
/// <summary>
/// Gets token info.
/// </summary>
/// <param name="code">Authorization Code.</param>
/// <param name="redirectUri">Redirect uri.</param>
/// <param name="cancellationToken"><see cref="CancellationToken"/> to be used for cancellation.</param>
/// <returns><see cref="SparkResult{TSparkObject}"/> to get result.</returns>
public async Task< SparkResult<TokenInfo> > GetTokenInfoAsync(string code, string redirectUri, CancellationToken? cancellationToken = null)
{
var parameters = new NameValueCollection();
parameters.Add("grant_type", "authorization_code");
parameters.Add("client_id", this.clientId);
parameters.Add("client_secret", this.clientSecret);
parameters.Add("code", code);
parameters.Add("redirect_uri", redirectUri);
return await getTokenInfoAsync(parameters, cancellationToken);
}
/// <summary>
/// Refreshed token info.
/// </summary>
/// <param name="refreshToken">Refresh Code.</param>
/// <param name="cancellationToken"><see cref="CancellationToken"/> to be used for cancellation.</param>
/// <returns><see cref="SparkResult{TSparkObject}"/> to get result.</returns>
public async Task< SparkResult<TokenInfo> > RefreshTokenInfoAsync(string refreshToken, CancellationToken? cancellationToken = null)
{
var parameters = new NameValueCollection();
parameters.Add("grant_type", "refresh_token");
parameters.Add("client_id", this.clientId);
parameters.Add("client_secret", this.clientSecret);
parameters.Add("refresh_token", refreshToken);
return await getTokenInfoAsync(parameters, cancellationToken);
}
/// <summary>
/// Refreshed token info.
/// </summary>
/// <param name="tokenInfo">Refresh Code.</param>
/// <param name="cancellationToken"><see cref="CancellationToken"/> to be used for cancellation.</param>
/// <returns><see cref="SparkResult{TSparkObject}"/> to get result.</returns>
public async Task< SparkResult<TokenInfo> > RefreshTokenInfoAsync(TokenInfo tokenInfo, CancellationToken? cancellationToken = null)
{
return await RefreshTokenInfoAsync(tokenInfo.RefreshToken, cancellationToken);
}
}
}
| 38.226852 | 147 | 0.62226 | [
"MIT"
] | thrzn41/CiscoSparkAPIClient | CSharp/MultiTarget.Thrzn41.CiscoSpark/Version1/OAuth2/SparkOAuth2Client.cs | 8,259 | C# |
using Microsoft.Extensions.Configuration;
namespace StravaUpload.Console
{
public class Configuration : IConfiguration
{
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private readonly IConfigurationRoot root;
public Configuration()
{
}
public Configuration(IConfigurationRoot root)
{
this.root = root;
this.MovescountAppKey = this.root["AppConfig:MovescountAppKey"];
this.MovescountUserEmail = this.root["AppConfig:MovescountUserEmail"];
this.MovescountUserKey = this.root["AppConfig:MovescountUserKey"];
this.MovescountMemberName = this.root["AppConfig:MovescountMemberName"];
this.CookieValue = this.root["AppConfig:CookieValue"];
this.StorageConnectionString = this.root["AppConfig:StorageConnectionString"];
this.BackupDir = this.root["AppConfig:BackupDir"];
this.ContainerName = this.root["AppConfig:ContainerName"];
this.GarminConnectClientBackupDir = this.root["AppConfig:GarminConnectClientBackupDir"];
this.GarminConnectClientContainerName = this.root["AppConfig:GarminConnectClientContainerName"];
this.MovescountBackupBackupDir = this.root["AppConfig:MovescountBackupBackupDir"];
this.MovescountBackupContainerName = this.root["AppConfig:MovescountBackupContainerName"];
this.StravaAccessToken = this.root["AppConfig:StravaAccessToken"];
this.SendGridApiKey = this.root["AppConfig:SendGridApiKey"];
this.EmailFrom = this.root["AppConfig:EmailFrom"];
this.EmailTo = this.root["AppConfig:EmailTo"];
this.Username = this.root["AppConfig:Username"];
this.Password = this.root["AppConfig:Password"];
}
public string MovescountAppKey { get; set; }
public string MovescountUserEmail { get; set; }
public string MovescountUserKey { get; set; }
public string MovescountMemberName { get; set; }
public string BackupDir { get; set; }
public string CookieValue { get; set; }
public string StorageConnectionString { get; set; }
public string ContainerName { get; set; }
public string StravaAccessToken { get; set; }
public string SendGridApiKey { get; set; }
public string EmailFrom { get; set; }
public string EmailTo { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string MovescountBackupBackupDir { get; set; }
public string MovescountBackupContainerName { get; set; }
public string GarminConnectClientBackupDir { get; set; }
public string GarminConnectClientContainerName { get; set; }
}
} | 38.256757 | 108 | 0.667609 | [
"MIT"
] | marazt/strava-upload | StravaUpload.Console/Configuration.cs | 2,833 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Bungie.net API Client for .NET")]
[assembly: AssemblyCopyright("Copyright © 2018-2019 Benn Benson")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.1.2")]
[assembly: AssemblyFileVersion("0.1.2")]
[assembly: AssemblyInformationalVersion("0.1.2 for API version 2.3.6")]
#if SIGNED
[assembly: InternalsVisibleTo("MadReflection.BungieNetApi.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a5319e6aa91a47e3a83f39db873f1f39bc80c96a2199524158365d4b4e0f8433bd6259fb4e3fb895e9d4d953385356433852d268daaad0bfacf75d431f0e7bfe51315ee64eafbdf5bcfbb4e903db1ae4025312bc07aea73f0470e5cd297f23110462e85df4fbbde120cf9cfbff0785857372bd91810bb1e43c6cd5b2a713099f")]
#else
[assembly: InternalsVisibleTo("MadReflection.BungieNetApi.Tests")]
#endif | 49.315789 | 398 | 0.855923 | [
"BSD-3-Clause"
] | KiaArmani/XurSuite | Libraries/MadReflection.BungieApi/Shared/CommonAssemblyInfo.cs | 940 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. 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.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.TestHost;
using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class CompositeViewEngineTests
{
private readonly IServiceProvider _services = TestHelper.CreateServices("CompositeViewEngine");
private readonly Action<IApplicationBuilder> _app = new CompositeViewEngine.Startup().Configure;
[Fact]
public async Task CompositeViewEngine_FindsPartialViewsAcrossAllEngines()
{
// Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync("http://localhost/");
// Assert
Assert.Equal("Hello world", body.Trim());
}
[Fact]
public async Task CompositeViewEngine_FindsViewsAcrossAllEngines()
{
// Arrange
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
// Act
var body = await client.GetStringAsync("http://localhost/Home/TestView");
// Assert
Assert.Equal("Content from test view", body.Trim());
}
}
} | 32.866667 | 111 | 0.64503 | [
"Apache-2.0"
] | ardalis/Mvc | test/Microsoft.AspNet.Mvc.FunctionalTests/CompositeViewEngineTests.cs | 1,481 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** 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.AzureNextGen.MachineLearningServices.V20180301Preview.Inputs
{
/// <summary>
/// A Machine Learning compute based on Azure BatchAI.
/// </summary>
public sealed class BatchAIArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Location for the underlying compute
/// </summary>
[Input("computeLocation")]
public Input<string>? ComputeLocation { get; set; }
/// <summary>
/// The type of compute
/// </summary>
[Input("computeType", required: true)]
public Input<string> ComputeType { get; set; } = null!;
/// <summary>
/// The description of the Machine Learning compute.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// BatchAI properties
/// </summary>
[Input("properties")]
public Input<Inputs.BatchAIPropertiesArgs>? Properties { get; set; }
/// <summary>
/// ARM resource id of the compute
/// </summary>
[Input("resourceId")]
public Input<string>? ResourceId { get; set; }
public BatchAIArgs()
{
}
}
}
| 28.811321 | 81 | 0.593975 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/MachineLearningServices/V20180301Preview/Inputs/BatchAIArgs.cs | 1,527 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InmobiliariaLogicLayer.Lotes
{
public class Lote: ILoteComponent
{
//private double Id;
//variable que obtiene el precio de la base de datos.
//public Lote(double Id)
//{
//this.precioOne = precioOne;
//}
public double calcularCostoLote()
{
return 65000;
//return precioOne;
}
public double calcularSaldoLote()
{
return 65000;
}
}
}
| 19.741935 | 61 | 0.573529 | [
"MIT"
] | CBDELEON/cake | InmobiliariaLogicLayer/Lotes/Lote.cs | 614 | C# |
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using TodoApp.Authorization.Users;
namespace TodoApp.Sessions.Dto
{
[AutoMapFrom(typeof(User))]
public class UserLoginInfoDto : EntityDto<long>
{
public string Name { get; set; }
public string Surname { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
}
}
| 21.473684 | 51 | 0.659314 | [
"MIT"
] | SereneYi/TodoList-Backend | aspnet-core/src/TodoApp.Application/Sessions/Dto/UserLoginInfoDto.cs | 410 | C# |
using System;
namespace DailyCodingProblem
{
internal class Day34
{
private static int Main(string[] args)
{
Console.WriteLine(GetMinimumPalindrone("racecar"));
Console.WriteLine(GetMinimumPalindrone("race"));
Console.WriteLine(GetMinimumPalindrone("google"));
Console.ReadLine();
return 0;
}
private static string GetMinimumPalindrone(string text)
{
if (IsPalindrome(text))
{
return text;
}
if (text[0] == text[text.Length - 1])
{
return text[0] + GetMinimumPalindrone(text.Substring(1, text.Length - 2)) + text[text.Length - 1];
}
string firstPalindrome = text[0] + GetMinimumPalindrone(text.Substring(1)) + text[0];
string secondPalindrome = text[text.Length - 1] + GetMinimumPalindrone(text.Substring(0, text.Length - 1)) + text[text.Length - 1];
if (firstPalindrome.Length > secondPalindrome.Length)
{
return secondPalindrome;
}
else if (firstPalindrome.Length < secondPalindrome.Length)
{
return firstPalindrome;
}
else
{
return string.Compare(firstPalindrome, secondPalindrome) <= 0 ? firstPalindrome : secondPalindrome;
}
}
private static bool IsPalindrome(string text)
{
char[] chars = text.ToCharArray();
Array.Reverse(chars);
return text == new string(chars);
}
}
} | 23.654545 | 134 | 0.685626 | [
"MIT"
] | LucidSigma/Daily-Coding-Problems | Days 031 - 040/Day 34/GetMinimumPalindrome.cs | 1,301 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// PriorityQueue implementation from: http://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx
public class PriorityQueue<T> where T : IComparable<T>
{
private List<T> data;
public void Clear()
{
data.Clear();
}
public PriorityQueue()
{
this.data = new List<T>();
}
public void Enqueue(T item)
{
data.Add(item);
int ci = data.Count - 1; // child index; start at end
while (ci > 0)
{
int pi = (ci - 1) / 2; // parent index
if (data[ci].CompareTo(data[pi]) >= 0) break; // child item is larger than (or equal) parent so we're done
T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp;
ci = pi;
}
}
public T Dequeue()
{
// assumes pq is not empty; up to calling code
int li = data.Count - 1; // last index (before removal)
T frontItem = data[0]; // fetch the front
data[0] = data[li];
data.RemoveAt(li);
--li; // last index (after removal)
int pi = 0; // parent index. start at front of pq
while (true)
{
int ci = pi * 2 + 1; // left child index of parent
if (ci > li) break; // no children so done
int rc = ci + 1; // right child
if (rc <= li && data[rc].CompareTo(data[ci]) < 0) // if there is a rc (ci + 1), and it is smaller than left child, use the rc instead
ci = rc;
if (data[pi].CompareTo(data[ci]) <= 0) break; // parent is smaller than (or equal to) smallest child so done
T tmp = data[pi]; data[pi] = data[ci]; data[ci] = tmp; // swap parent and child
pi = ci;
}
return frontItem;
}
public T Peek()
{
T frontItem = data[0];
return frontItem;
}
public int Count()
{
return data.Count;
}
public override string ToString()
{
string s = "";
for (int i = 0; i < data.Count; ++i)
s += data[i].ToString() + " ";
s += "count = " + data.Count;
return s;
}
public bool IsConsistent()
{
// is the heap property true for all data?
if (data.Count == 0) return true;
int li = data.Count - 1; // last index
for (int pi = 0; pi < data.Count; ++pi) // each parent index
{
int lci = 2 * pi + 1; // left child index
int rci = 2 * pi + 2; // right child index
if (lci <= li && data[pi].CompareTo(data[lci]) > 0) return false; // if lc exists and it's greater than parent then bad.
if (rci <= li && data[pi].CompareTo(data[rci]) > 0) return false; // check the right child too.
}
return true; // passed all checks
} // IsConsistent
} // PriorityQueue | 31.180851 | 145 | 0.525077 | [
"MIT"
] | Jammie506/GE2-2020-2021 | Game Engines 2 Examples 2021/Assets/PriorityQueue.cs | 2,933 | C# |
using System;
using AppKit;
namespace LiteHtmlSharp.Mac
{
public interface ICustomTagView
{
bool HasSetup { get; }
void Setup(ElementInfo elementInfo);
NSView View { get; }
}
}
| 13.866667 | 42 | 0.649038 | [
"BSD-3-Clause"
] | PingmanTools/LiteHtmlSharp | LiteHtmlSharp.Mac/ICustomTagView.cs | 210 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Military_Elite.Enumeration
{
public enum SoldierCorpEnum
{
Airforces = 1,
Marines = 2
}
}
| 15.153846 | 36 | 0.670051 | [
"MIT"
] | StefanIvanovC/Homeworks-Softuni | C# OOP/Interfaces and Abstraction/InterfacesAndAbstraction/Military Elite/Enumeration/SoldierCorpEnum.cs | 199 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Novatel.Flex.Utilities;
namespace Novatel.Flex.Networking
{
internal class PacketWriter : EndianBinaryWriter
{
public PacketWriter()
: base(EndianBitConverter.Big, new MemoryStream())
{
}
public byte[] GetBytes()
{
var mem = (MemoryStream) BaseStream;
return mem.GetBuffer();
}
}
}
| 20.8 | 62 | 0.630769 | [
"MIT"
] | pushrbx/Novatel.Flex | Novatel.Flex/Networking/PacketWriter.cs | 522 | C# |
using FluentCommander.BulkCopy;
using FluentCommander.EntityFramework;
using FluentCommander.IntegrationTests.EntityFramework.SqlServer.Entities;
using FluentCommander.Samples.Setup.Entities;
using Microsoft.Data.SqlClient;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Data;
using Xunit;
using Xunit.Abstractions;
namespace FluentCommander.IntegrationTests.EntityFramework.SqlServer.Commands
{
[Collection("Service Provider collection")]
public class BulkCopyIntegrationTest : EntityFrameworkSqlServerIntegrationTest<DatabaseCommanderDomainContext>
{
private const int RowCount = 100;
public BulkCopyIntegrationTest(ServiceProviderFixture serviceProviderFixture, ITestOutputHelper output)
: base(serviceProviderFixture, output) { }
[Fact]
public void ExecuteBulkCopy_ShouldCreateNewRows_WhenUsingAutoMapper()
{
// Arrange
DataTable dataTable = GetDataToInsert();
// Act
BulkCopyResult result = SUT.BuildCommand()
.ForBulkCopy()
.From(dataTable)
.Into("[dbo].[SampleTable]")
.Mapping(opt => opt.UseAutoMap())
.Execute();
// Assert
result.ShouldNotBeNull();
result.RowCountCopied.ShouldBe(RowCount);
// Print
WriteLine(RowCount);
}
[Fact]
public void ExecuteBulkCopy_ShouldCreateNewRows_WhenUsingPartialMapper()
{
// Arrange
DataTable dataTable = GetDataToInsert();
// Alter the DataTable to simulate a source where the SampleVarChar field is named something different
dataTable.Columns["SampleVarChar"].ColumnName = "SampleString";
// Now specify the mapping
var columnMapping = new ColumnMapping
{
ColumnMaps = new List<ColumnMap>
{
new ColumnMap("SampleString", "SampleVarChar")
}
};
// Act
BulkCopyResult result = SUT.BuildCommand()
.ForBulkCopy()
.From(dataTable)
.Into("[dbo].[SampleTable]")
.Mapping(opt => opt.UsePartialMap(columnMapping))
.Execute();
// Assert
result.ShouldNotBeNull();
result.RowCountCopied.ShouldBe(RowCount);
// Print
WriteLine(RowCount);
}
[Fact]
public void ExecuteBulkCopy_ShouldCreateNewRows_WhenUsingMap()
{
// Arrange
DataTable dataTable = GetDataToInsert();
// Alter the DataTable to simulate a source where all column names are different than the destination
dataTable.Columns["SampleInt"].ColumnName = "Column1";
dataTable.Columns["SampleSmallInt"].ColumnName = "Column2";
dataTable.Columns["SampleTinyInt"].ColumnName = "Column3";
dataTable.Columns["SampleBit"].ColumnName = "Column4";
dataTable.Columns["SampleDecimal"].ColumnName = "Column5";
dataTable.Columns["SampleFloat"].ColumnName = "Column6";
dataTable.Columns["SampleVarChar"].ColumnName = "Column7";
// Now specify the mapping
var columnMapping = new ColumnMapping
{
ColumnMaps = new List<ColumnMap>
{
new ColumnMap("Column1", "SampleInt"),
new ColumnMap("Column2", "SampleSmallInt"),
new ColumnMap("Column3", "SampleTinyInt"),
new ColumnMap("Column4", "SampleBit"),
new ColumnMap("Column5", "SampleDecimal"),
new ColumnMap("Column6", "SampleFloat"),
new ColumnMap("Column7", "SampleVarChar"),
}
};
// Act
BulkCopyResult result = SUT.BuildCommand()
.ForBulkCopy()
.From(dataTable)
.Into("[dbo].[SampleTable]")
.Mapping(opt => opt.UseMap(columnMapping))
.Execute();
// Assert
result.ShouldNotBeNull();
result.RowCountCopied.ShouldBe(RowCount);
// Print
WriteLine(RowCount);
}
[Fact]
public void ExecuteBulkCopyAsync_ShouldCreateNewRows_WhenUsingOptions()
{
// Arrange
DataTable dataTable = GetDataToInsert();
// Act
BulkCopyResult result = SUT.BuildCommand()
.ForBulkCopy()
.From(dataTable)
.Into("[dbo].[SampleTable]")
.Mapping(map => map.UseAutoMap())
.Options(options => options.KeepNulls().CheckConstraints().TableLock(false))
.Execute();
// Assert
result.ShouldNotBeNull();
result.RowCountCopied.ShouldBe(RowCount);
// Print
WriteLine(RowCount);
}
[Fact]
public void ExecuteBulkCopyAsync_ShouldCreateNewRows_WhenUsingOrderHints()
{
// Arrange
DataTable dataTable = GetDataToInsert();
// Act
BulkCopyResult result = SUT.BuildCommand()
.ForBulkCopy()
.From(dataTable)
.Into("[dbo].[SampleTable]")
.Mapping(map => map.UseAutoMap())
.OrderHints(hints => hints.OrderBy("SampleInt").OrderByDescending("SampleSmallInt"))
.Execute();
// Assert
result.ShouldNotBeNull();
result.RowCountCopied.ShouldBe(RowCount);
// Print
WriteLine(RowCount);
}
[Fact]
public void ExecuteBulkCopyAsync_ShouldCreateNewRows_WhenUsingEvents()
{
// Arrange
DataTable dataTable = GetDataToInsert();
// Act
BulkCopyResult result = SUT.BuildCommand()
.ForBulkCopy()
.From(dataTable)
.Into("[dbo].[SampleTable]")
.Mapping(map => map.UseAutoMap())
.Events(events => events.NotifyAfter(10).OnRowsCopied((sender, e) =>
{
var sqlRowsCopiedEventArgs = (SqlRowsCopiedEventArgs)e;
WriteLine($"Total rows copied: {sqlRowsCopiedEventArgs.RowsCopied}");
}))
.Execute();
// Assert
result.ShouldNotBeNull();
result.RowCountCopied.ShouldBe(RowCount);
// Print
WriteLine(RowCount);
}
[Fact]
public void ExecuteBulkCopyAsync_ShouldCreateNewRows_WhenUsingAllApis()
{
// Arrange
DataTable dataTable = GetDataToInsert();
// Alter the DataTable to simulate a source where the SampleVarChar field is named something different
dataTable.Columns["SampleVarChar"].ColumnName = "SampleString";
// Act
BulkCopyResult result = SUT.BuildCommand()
.ForBulkCopy<SampleEntity>()
.From(dataTable, DataRowState.Added)
.Into("[dbo].[SampleTable]")
.Options(options => options.KeepNulls().CheckConstraints().TableLock(false))
.OrderHints(hints => hints.OrderBy("SampleInt").OrderByDescending("SampleSmallInt"))
.BatchSize(100)
.Timeout(TimeSpan.FromSeconds(30))
.Mapping(mapping => mapping.UsePartialMap(sample =>
{
sample.Property(s => s.SampleVarChar).MapFrom("SampleString");
}))
.Events(events => events.NotifyAfter(10).OnRowsCopied((sender, e) =>
{
var sqlRowsCopiedEventArgs = (SqlRowsCopiedEventArgs)e;
WriteLine($"Total rows copied: {sqlRowsCopiedEventArgs.RowsCopied}");
}))
.OrderHints(hints => hints.Build(entity =>
{
entity.Property(e => e.SampleInt).OrderByDescending();
}))
.Execute();
// Assert
result.ShouldNotBeNull();
result.RowCountCopied.ShouldBe(RowCount);
// Print
WriteLine(RowCount);
}
private DataTable GetDataToInsert()
{
DataTable dataTable = ExecuteSql("SELECT * FROM [dbo].[SampleTable] WHERE 1 = 0");
for (int i = 0; i < RowCount; i++)
{
DataRow dataRow = dataTable.NewRow();
dataRow["SampleInt"] = 1;
dataRow["SampleSmallInt"] = 1;
dataRow["SampleTinyInt"] = 1;
dataRow["SampleBit"] = true;
dataRow["SampleDecimal"] = 1;
dataRow["SampleFloat"] = 1;
dataRow["SampleDateTime"] = DateTime.UtcNow;
dataRow["SampleUniqueIdentifier"] = Guid.NewGuid();
dataRow["SampleVarChar"] = $"Row {i + 4}";
dataRow["CreatedBy"] = TestUsername;
dataRow["CreatedDate"] = Timestamp;
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
}
}
| 35.197761 | 114 | 0.542351 | [
"MIT"
] | relay-dev/fluent-commander | tests/FluentCommander.IntegrationTests.EntityFramework.SqlServer/Commands/BulkCopyIntegrationTest.cs | 9,435 | C# |
using System.Numerics;
namespace AdventOfCode.Year2019;
public class IntcodeComputer
{
private BigInteger[] _memory;
private int _counter;
private int _relbase;
private bool _halted;
public IntcodeComputer(string memory)
: this(memory.Split(',').Select(BigInteger.Parse).ToArray())
{
}
public IntcodeComputer(BigInteger[] memory)
{
_memory = memory;
}
public Func<Task<BigInteger>> Input { get; set; }
public Func<BigInteger, Task> Output { get; set; }
public void Halt()
{
_halted = true;
}
public BigInteger Get(int address)
{
return _memory[address];
}
public void Set(int address, BigInteger value)
{
_memory[address] = value;
}
public async Task RunAsync(CancellationToken token = default)
{
while (!_halted && !token.IsCancellationRequested)
{
var opcode = (int)(_memory[_counter] % 100);
var modes = (int)(_memory[_counter] / 100);
switch (opcode)
{
case 1:
Memory(3, modes) = Memory(1, modes) + Memory(2, modes);
_counter += 4;
break;
case 2:
Memory(3, modes) = Memory(1, modes) * Memory(2, modes);
_counter += 4;
break;
case 3:
var input = await Input();
Memory(1, modes) = input;
_counter += 2;
break;
case 4:
await Output(Memory(1, modes));
_counter += 2;
break;
case 5:
_counter = Memory(1, modes) != 0 ? (int)Memory(2, modes) : _counter + 3;
break;
case 6:
_counter = Memory(1, modes) == 0 ? (int)Memory(2, modes) : _counter + 3;
break;
case 7:
Memory(3, modes) = Memory(1, modes) < Memory(2, modes) ? 1 : 0;
_counter += 4;
break;
case 8:
Memory(3, modes) = Memory(1, modes) == Memory(2, modes) ? 1 : 0;
_counter += 4;
break;
case 9:
_relbase += (int)Memory(1, modes);
_counter += 2;
break;
case 99:
return;
default:
throw new InvalidOperationException();
}
}
}
private ref BigInteger Memory(int offset, int modes)
{
switch (modes / (int)Math.Pow(10, offset - 1) % 10)
{
case 0:
{
var address = _counter + offset;
EnsureMemory(address);
address = (int)_memory[address];
EnsureMemory(address);
return ref _memory[address];
}
case 1:
{
var address = _counter + offset;
EnsureMemory(address);
return ref _memory[address];
}
case 2:
{
var address = _counter + offset;
EnsureMemory(address);
address = _relbase + (int)_memory[address];
EnsureMemory(address);
return ref _memory[address];
}
default: throw new NotSupportedException();
}
}
private void EnsureMemory(int address)
{
if (address < _memory.Length)
{
return;
}
var memory = new BigInteger[address + 1];
_memory.AsSpan().CopyTo(memory);
_memory = memory;
}
}
| 20.80597 | 77 | 0.614778 | [
"MIT"
] | sehra/advent-of-code | AdventOfCode/Year2019/IntcodeComputer.cs | 2,790 | C# |
using System;
using Gtk;
using Gamma.Binding.Core;
using Gamma.Utilities;
using System.Linq.Expressions;
namespace Gamma.GtkWidgets
{
[System.ComponentModel.ToolboxItem (true)]
[System.ComponentModel.Category ("Gamma Gtk")]
public class yTextView : TextView
{
public BindingControler<yTextView> Binding { get; private set;}
public yTextView ()
{
Binding = new BindingControler<yTextView> (this, new Expression<Func<yTextView, object>>[] {
(w => w.Buffer.Text)
});
Buffer.Changed += Buffer_Changed;
}
void Buffer_Changed (object sender, EventArgs e)
{
Binding.FireChange (w => w.Buffer.Text);
}
}
}
| 21.266667 | 95 | 0.710031 | [
"Apache-2.0"
] | Art8m/QSProjects | Binding/Gamma.Binding/GtkWidgets/yTextView.cs | 640 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Service.Interface")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Service.Interface")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("569cc197-f0d4-430f-9ced-c97aab165b2b")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.810811 | 56 | 0.715183 | [
"MIT"
] | myloveCc/WcfHoster | Service.Interface/Properties/AssemblyInfo.cs | 1,306 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ServerNodeIdentityAndKey.cs" company="Sean McElroy">
// Copyright Sean McElroy; released as open-source software under the licensing terms of the MIT License.
// </copyright>
// <summary>
// An identity of a node consisting of a date of generation, key pair, and nonce proving the date and public key
// meet a target difficulty requirement. It also includes the private key for local serialization and storage.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Mystiko.Net
{
using System;
using JetBrains.Annotations;
/// <summary>
/// An identity of a node consisting of a date of generation, key pair, and nonce proving the date and public key
/// meet a target difficulty requirement. It also includes the private key for local serialization and storage.
/// </summary>
public sealed class ServerNodeIdentityAndKey : ServerNodeIdentity
{
/// <summary>
/// Gets or sets the byte array of the private key
/// </summary>
[NotNull]
public byte[] PrivateKey { get; }
public ServerNodeIdentityAndKey(ulong dateEpoch, [NotNull] byte[] publicKeyX, [NotNull] byte[] publicKeyY, ulong nonce, [NotNull] byte[] privateKey)
: base(dateEpoch, publicKeyX, publicKeyY, nonce)
{
this.PrivateKey = privateKey ?? throw new ArgumentNullException(nameof(privateKey));
}
}
}
| 45.222222 | 156 | 0.584767 | [
"MIT"
] | seanmcelroy/Mystiko | Mystiko.Library.Core/Net/ServerNodeIdentityAndKey.cs | 1,630 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.PowerPointApi;
namespace NetOffice.PowerPointApi.Behind
{
/// <summary>
/// DispatchInterface MediaFormat
/// SupportByVersion PowerPoint, 14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744263.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
public class MediaFormat : COMObject, NetOffice.PowerPointApi.MediaFormat
{
#pragma warning disable
#region Type Information
/// <summary>
/// Contract Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type ContractType
{
get
{
if(null == _contractType)
_contractType = typeof(NetOffice.PowerPointApi.MediaFormat);
return _contractType;
}
}
private static Type _contractType;
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(MediaFormat);
return _type;
}
}
#endregion
#region Ctor
/// <summary>
/// Stub Ctor, not indented to use
/// </summary>
public MediaFormat() : base()
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744541.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public NetOffice.PowerPointApi.Application Application
{
get
{
return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.PowerPointApi.Application>(this, "Application", typeof(NetOffice.PowerPointApi.Application));
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745175.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16), ProxyResult]
public object Parent
{
get
{
return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746131.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Single Volume
{
get
{
return InvokerService.InvokeInternal.ExecuteSinglePropertyGet(this, "Volume");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Volume", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744385.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public bool Muted
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Muted");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Muted", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746068.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 Length
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "Length");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745838.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 StartPoint
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "StartPoint");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "StartPoint", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746105.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 EndPoint
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "EndPoint");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "EndPoint", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745782.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 FadeInDuration
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "FadeInDuration");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "FadeInDuration", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746771.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 FadeOutDuration
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "FadeOutDuration");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "FadeOutDuration", value);
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746520.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public NetOffice.PowerPointApi.MediaBookmarks MediaBookmarks
{
get
{
return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.PowerPointApi.MediaBookmarks>(this, "MediaBookmarks", typeof(NetOffice.PowerPointApi.MediaBookmarks));
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744315.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public NetOffice.PowerPointApi.Enums.PpMediaTaskStatus ResamplingStatus
{
get
{
return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.PowerPointApi.Enums.PpMediaTaskStatus>(this, "ResamplingStatus");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745895.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public bool IsLinked
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "IsLinked");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746271.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public bool IsEmbedded
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "IsEmbedded");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744842.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 AudioSamplingRate
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "AudioSamplingRate");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746132.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 VideoFrameRate
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "VideoFrameRate");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744903.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 SampleHeight
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "SampleHeight");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744690.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public Int32 SampleWidth
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "SampleWidth");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff744226.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public string VideoCompressionType
{
get
{
return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "VideoCompressionType");
}
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745256.aspx </remarks>
[SupportByVersion("PowerPoint", 14,15,16)]
public string AudioCompressionType
{
get
{
return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "AudioCompressionType");
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff745841.aspx </remarks>
/// <param name="position">Int32 position</param>
[SupportByVersion("PowerPoint", 14,15,16)]
public void SetDisplayPicture(Int32 position)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "SetDisplayPicture", position);
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746677.aspx </remarks>
/// <param name="filePath">string filePath</param>
[SupportByVersion("PowerPoint", 14,15,16)]
public void SetDisplayPictureFromFile(string filePath)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "SetDisplayPictureFromFile", filePath);
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746339.aspx </remarks>
/// <param name="trim">optional bool Trim = false</param>
/// <param name="sampleHeight">optional Int32 SampleHeight = 768</param>
/// <param name="sampleWidth">optional Int32 SampleWidth = 1280</param>
/// <param name="videoFrameRate">optional Int32 VideoFrameRate = 24</param>
/// <param name="audioSamplingRate">optional Int32 AudioSamplingRate = 48000</param>
/// <param name="videoBitRate">optional Int32 VideoBitRate = 7000000</param>
[SupportByVersion("PowerPoint", 14,15,16)]
public void Resample(object trim, object sampleHeight, object sampleWidth, object videoFrameRate, object audioSamplingRate, object videoBitRate)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "Resample", new object[]{ trim, sampleHeight, sampleWidth, videoFrameRate, audioSamplingRate, videoBitRate });
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746339.aspx </remarks>
[CustomMethod]
[SupportByVersion("PowerPoint", 14,15,16)]
public void Resample()
{
InvokerService.InvokeInternal.ExecuteMethod(this, "Resample");
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746339.aspx </remarks>
/// <param name="trim">optional bool Trim = false</param>
[CustomMethod]
[SupportByVersion("PowerPoint", 14,15,16)]
public void Resample(object trim)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "Resample", trim);
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746339.aspx </remarks>
/// <param name="trim">optional bool Trim = false</param>
/// <param name="sampleHeight">optional Int32 SampleHeight = 768</param>
[CustomMethod]
[SupportByVersion("PowerPoint", 14,15,16)]
public void Resample(object trim, object sampleHeight)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "Resample", trim, sampleHeight);
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746339.aspx </remarks>
/// <param name="trim">optional bool Trim = false</param>
/// <param name="sampleHeight">optional Int32 SampleHeight = 768</param>
/// <param name="sampleWidth">optional Int32 SampleWidth = 1280</param>
[CustomMethod]
[SupportByVersion("PowerPoint", 14,15,16)]
public void Resample(object trim, object sampleHeight, object sampleWidth)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "Resample", trim, sampleHeight, sampleWidth);
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746339.aspx </remarks>
/// <param name="trim">optional bool Trim = false</param>
/// <param name="sampleHeight">optional Int32 SampleHeight = 768</param>
/// <param name="sampleWidth">optional Int32 SampleWidth = 1280</param>
/// <param name="videoFrameRate">optional Int32 VideoFrameRate = 24</param>
[CustomMethod]
[SupportByVersion("PowerPoint", 14,15,16)]
public void Resample(object trim, object sampleHeight, object sampleWidth, object videoFrameRate)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "Resample", trim, sampleHeight, sampleWidth, videoFrameRate);
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746339.aspx </remarks>
/// <param name="trim">optional bool Trim = false</param>
/// <param name="sampleHeight">optional Int32 SampleHeight = 768</param>
/// <param name="sampleWidth">optional Int32 SampleWidth = 1280</param>
/// <param name="videoFrameRate">optional Int32 VideoFrameRate = 24</param>
/// <param name="audioSamplingRate">optional Int32 AudioSamplingRate = 48000</param>
[CustomMethod]
[SupportByVersion("PowerPoint", 14,15,16)]
public void Resample(object trim, object sampleHeight, object sampleWidth, object videoFrameRate, object audioSamplingRate)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "Resample", new object[]{ trim, sampleHeight, sampleWidth, videoFrameRate, audioSamplingRate });
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746706.aspx </remarks>
/// <param name="profile">optional NetOffice.PowerPointApi.Enums.PpResampleMediaProfile profile = 2</param>
[SupportByVersion("PowerPoint", 14,15,16)]
public void ResampleFromProfile(object profile)
{
InvokerService.InvokeInternal.ExecuteMethod(this, "ResampleFromProfile", profile);
}
/// <summary>
/// SupportByVersion PowerPoint 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff746706.aspx </remarks>
[CustomMethod]
[SupportByVersion("PowerPoint", 14,15,16)]
public void ResampleFromProfile()
{
InvokerService.InvokeInternal.ExecuteMethod(this, "ResampleFromProfile");
}
#endregion
#pragma warning restore
}
}
| 31.877159 | 186 | 0.689246 | [
"MIT"
] | igoreksiz/NetOffice | Source/PowerPoint/Behind/DispatchInterfaces/MediaFormat.cs | 16,610 | C# |
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
using RimWorld.Planet;
namespace MoreFactionInteraction
{
using JetBrains.Annotations;
[UsedImplicitly]
public class IncidentWorker_SpreadingOutpost : IncidentWorker
{
private Faction faction;
private static List<Map> tmpAvailableMaps = new List<Map>();
private readonly int minDist = 8;
private readonly int maxDist = 30;
private readonly int maxSites = 20;
public override float AdjustedChance => base.AdjustedChance * MoreFactionInteraction_Settings.pirateBaseUpgraderModifier;
protected override bool CanFireNowSub(IncidentParms parms)
{
return base.CanFireNowSub(parms: parms) && TryFindFaction(enemyFaction: out this.faction)
&& TileFinder.TryFindNewSiteTile(tile: out int tile, minDist, maxDist)
&& this.TryGetRandomAvailableTargetMap(out Map map)
&& Find.World.worldObjects.Sites.Count() <= maxSites;
}
protected override bool TryExecuteWorker(IncidentParms parms)
{
if (!TryFindFaction(enemyFaction: out this.faction))
return false;
if (!this.TryGetRandomAvailableTargetMap(map: out Map map))
return false;
if (faction.leader == null)
return false;
int pirateTile = this.RandomNearbyHostileSettlement(map.Tile)?.Tile ?? Tile.Invalid;
if (pirateTile == Tile.Invalid)
return false;
if (!TileFinder.TryFindNewSiteTile(tile: out int tile, minDist: 2, maxDist: 8, allowCaravans: false, preferCloserTiles: true, nearThisTile: pirateTile))
return false;
Site site = SiteMaker.MakeSite(core: SiteCoreDefOf.Nothing, sitePart: SitePartDefOf.Outpost, tile: tile, faction: this.faction);
site.Tile = tile;
site.sitePartsKnown = true;
Find.WorldObjects.Add(o: site);
this.SendStandardLetter(lookTargets: site, relatedFaction: this.faction, textArgs: new string[]
{
(this.faction.leader?.LabelShort ?? "MFI_Representative".Translate()), this.faction.def.leaderTitle, this.faction.Name,
});
return true;
}
private SettlementBase RandomNearbyHostileSettlement(int originTile)
{
return (from settlement in Find.WorldObjects.SettlementBases
where settlement.Attackable && Find.WorldGrid.ApproxDistanceInTiles(firstTile: originTile, secondTile: settlement.Tile) < 36f
&& Find.WorldReachability.CanReach(startTile: originTile, destTile: settlement.Tile) && settlement.Faction == this.faction
select settlement).RandomElementWithFallback();
}
private static bool TryFindFaction(out Faction enemyFaction)
{
if (Find.FactionManager.AllFactions
.Where(x => !x.def.hidden && !x.defeated && x.HostileTo(other: Faction.OfPlayer) && x.def.permanentEnemy)
.TryRandomElement(result: out enemyFaction))
return true;
enemyFaction = null;
return false;
}
private bool TryGetRandomAvailableTargetMap(out Map map)
{
tmpAvailableMaps.Clear();
List<Map> maps = Find.Maps;
foreach (Map potentialTargetMap in maps)
{
if (potentialTargetMap.IsPlayerHome && this.RandomNearbyHostileSettlement(originTile: potentialTargetMap.Tile) != null)
{
tmpAvailableMaps.Add(item: potentialTargetMap);
}
}
bool result = tmpAvailableMaps.TryRandomElement(result: out map);
tmpAvailableMaps.Clear();
return result;
}
}
}
| 43.193548 | 164 | 0.609908 | [
"MIT"
] | Proxyer/MoreFactionInteraction | MoreFactionInteraction/Spreading Pirates/IncidentWorker_SpreadingOutpost.cs | 4,019 | C# |
using IQFeed.CSharpApiClient.Lookup.Symbol.Messages;
using IQFeed.CSharpApiClient.Tests.Common;
using NUnit.Framework;
namespace IQFeed.CSharpApiClient.Tests.Lookup.Symbol.Messages
{
public class SymbolByFilterMessageTests
{
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_SymbolByFilterMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "E,7,1,ENI,";
// Act
var symbolByFilterMessageParsed = SymbolByFilterMessage.Parse(message);
var symbolByFilterMessage = new SymbolByFilterMessage("E", 7, 1, "ENI");
// Assert
Assert.AreEqual(symbolByFilterMessageParsed, symbolByFilterMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_SymbolByFilterMessage_WithCommasInDescription(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "Z,1,1,A,B,C,D,";
// Act
var symbolByFilterMessageParsed = SymbolByFilterMessage.Parse(message);
var symbolByFilterMessage = new SymbolByFilterMessage("Z", 1, 1, "A,B,C,D");
// Assert
Assert.AreEqual(symbolByFilterMessageParsed, symbolByFilterMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_ParseWithRequestId_SymbolByFilterMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "TESTREQUEST,BRSI,3,1,BALLISTIC RECOVERY SYSTEMS, IN,";
// Act
var symbolByFilterMessageParsed = SymbolByFilterMessage.ParseWithRequestId(message);
var symbolByFilterMessage = new SymbolByFilterMessage("BRSI", 3, 1, "BALLISTIC RECOVERY SYSTEMS, IN", "TESTREQUEST");
// Assert
Assert.AreEqual(symbolByFilterMessageParsed, symbolByFilterMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_SymbolBySicCodeMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "8322,PRSC,1,1,PROVIDENCE SERVICE CORP,";
// Act
var symbolBySicCodeMessageParsed = SymbolBySicCodeMessage.Parse(message);
var symbolBySicCodeMessage = new SymbolBySicCodeMessage(8322, "PRSC", 1, 1, "PROVIDENCE SERVICE CORP");
// Assert
Assert.AreEqual(symbolBySicCodeMessageParsed, symbolBySicCodeMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_SymbolBySicCodeMessage_WithCommasInDescription(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "8322,PRSC,1,1,PROVIDENCE,SERVICE,CORP,";
// Act
var symbolBySicCodeMessageParsed = SymbolBySicCodeMessage.Parse(message);
var symbolBySicCodeMessage = new SymbolBySicCodeMessage(8322, "PRSC", 1, 1, "PROVIDENCE,SERVICE,CORP");
// Assert
Assert.AreEqual(symbolBySicCodeMessageParsed, symbolBySicCodeMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_ParseWithRequestId_SymbolBySicCodeMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "TESTREQUEST,8361,CHCR,4,1,COMPREHENSIVE CARE,";
// Act
var symbolBySicCodeMessageParsed = SymbolBySicCodeMessage.ParseWithRequestId(message);
var symbolBySicCodeMessage = new SymbolBySicCodeMessage(8361, "CHCR", 4, 1, "COMPREHENSIVE CARE", "TESTREQUEST");
// Assert
Assert.AreEqual(symbolBySicCodeMessageParsed, symbolBySicCodeMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_SymbolByNaicsCodeMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "924110,EESC,4,1,EASTERN ENVTL SOLTNS CP,";
// Act
var symbolByNaicsCodeMessageParsed = SymbolByNaicsCodeMessage.Parse(message);
var symbolByNaicsCodeMessage = new SymbolByNaicsCodeMessage(924110, "EESC", 4, 1, "EASTERN ENVTL SOLTNS CP");
// Assert
Assert.AreEqual(symbolByNaicsCodeMessageParsed, symbolByNaicsCodeMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_SymbolByNaicsCodeMessage_WithCommasInDescription(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "924110,EESC,4,1,EASTERN ENVTL SOLTNS, CP,";
// Act
var symbolByNaicsCodeMessageParsed = SymbolByNaicsCodeMessage.Parse(message);
var symbolByNaicsCodeMessage = new SymbolByNaicsCodeMessage(924110, "EESC", 4, 1, "EASTERN ENVTL SOLTNS, CP");
// Assert
Assert.AreEqual(symbolByNaicsCodeMessageParsed, symbolByNaicsCodeMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_ParseWithRequestId_SymbolByNaicsCodeMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "TESTREQUEST,928110,TCNH,4,1,TECHNEST HOLDINGS INC,";
// Act
var symbolByNaicsCodeMessageParsed = SymbolByNaicsCodeMessage.ParseWithRequestId(message);
var symbolByNaicsCodeMessage = new SymbolByNaicsCodeMessage(928110, "TCNH", 4, 1, "TECHNEST HOLDINGS INC", "TESTREQUEST");
// Assert
Assert.AreEqual(symbolByNaicsCodeMessageParsed, symbolByNaicsCodeMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_ListedMarketMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "2,NCM,National Capital Market,5,NASDAQ,";
// Act
var listedMarketMessageParsed = ListedMarketMessage.Parse(message);
var listedMarketMessage = new ListedMarketMessage(2, "NCM", "National Capital Market", 5, "NASDAQ");
// Assert
Assert.AreEqual(listedMarketMessageParsed, listedMarketMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_ParseWithRequestId_ListedMarketMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "TESTREQUEST,7,NYSE,New York Stock Exchange,7,NYSE,";
// Act
var listedMarketMessageParsed = ListedMarketMessage.ParseWithRequestId(message);
var listedMarketMessage = new ListedMarketMessage(7, "NYSE", "New York Stock Exchange", 7, "NYSE", "TESTREQUEST");
// Assert
Assert.AreEqual(listedMarketMessageParsed, listedMarketMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_SecurityTypeMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "1,EQUITY,Equity,";
// Act
var securityTypeMessageParsed = SecurityTypeMessage.Parse(message);
var securityTypeMessage = new SecurityTypeMessage(1, "EQUITY", "Equity");
// Assert
Assert.AreEqual(securityTypeMessageParsed, securityTypeMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_ParseWithRequestId_SecurityTypeMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "TESTREQUEST,2,IEOPTION,Index/Equity Option,";
// Act
var securityTypeMessageParsed = SecurityTypeMessage.ParseWithRequestId(message);
var securityTypeMessage = new SecurityTypeMessage(2, "IEOPTION", "Index/Equity Option", "TESTREQUEST");
// Assert
Assert.AreEqual(securityTypeMessageParsed, securityTypeMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_TradeConditionMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "1,REGULAR,Normal Trade,";
// Act
var tradeConditionMessageParsed = TradeConditionMessage.Parse(message);
var tradeConditionMessage = new TradeConditionMessage(1, "REGULAR", "Normal Trade");
// Assert
Assert.AreEqual(tradeConditionMessageParsed, tradeConditionMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_ParseWithRequestId_TradeConditionMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "TESTREQUEST,21,SPLIT,Split Trade,";
// Act
var tradeConditionMessageParsed = TradeConditionMessage.ParseWithRequestId(message);
var tradeConditionMessage = new TradeConditionMessage(21, "SPLIT", "Split Trade", "TESTREQUEST");
// Assert
Assert.AreEqual(tradeConditionMessageParsed, tradeConditionMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_SicCodeInfoMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "0112,RICE,";
// Act
var sicCodeInfoMessageParsed = SicCodeInfoMessage.Parse(message);
var sicCodeInfoMessage = new SicCodeInfoMessage(112, "RICE");
// Assert
Assert.AreEqual(sicCodeInfoMessageParsed, sicCodeInfoMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_ParseWithRequestId_SicCodeInfoMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "TESTREQUEST,0133,SUGARCANE AND SUGAR BEETS,";
// Act
var sicCodeInfoMessageParsed = SicCodeInfoMessage.ParseWithRequestId(message);
var sicCodeInfoMessage = new SicCodeInfoMessage(133, "SUGARCANE AND SUGAR BEETS", "TESTREQUEST");
// Assert
Assert.AreEqual(sicCodeInfoMessageParsed, sicCodeInfoMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_Parse_NaicsCodeInfoMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "111110,Soybean Farming,";
// Act
var naicsCodeInfoMessageParsed = NaicsCodeInfoMessage.Parse(message);
var naicsCodeInfoMessage = new NaicsCodeInfoMessage(111110, "Soybean Farming");
// Assert
Assert.AreEqual(naicsCodeInfoMessageParsed, naicsCodeInfoMessage);
}
[Test, TestCaseSource(typeof(CultureNameTestCase), nameof(CultureNameTestCase.CultureNames))]
public void Should_ParseWithRequestId_NaicsCodeInfoMessage(string cultureName)
{
// Arrange
TestHelper.SetThreadCulture(cultureName);
var message = "TESTREQUEST,334220,Radio and Television Broadcasting and Wireless Communications Equipment Manufacturing,";
// Act
var naicsCodeInfoMessageParsed = NaicsCodeInfoMessage.ParseWithRequestId(message);
var naicsCodeInfoMessage = new NaicsCodeInfoMessage(334220, "Radio and Television Broadcasting and Wireless Communications Equipment Manufacturing", "TESTREQUEST");
// Assert
Assert.AreEqual(naicsCodeInfoMessageParsed, naicsCodeInfoMessage);
}
}
} | 44.602041 | 176 | 0.670251 | [
"MIT"
] | BunkerCoder/IQFeed.CSharpApiClient | src/IQFeed.CSharpApiClient.Tests/Lookup/Symbol/Messages/SymbolByFilterMessageTests.cs | 13,115 | C# |
using GDAPI.Attributes;
using GDAPI.Enumerations.GeometryDash;
namespace GDAPI.Objects.GeometryDash.LevelObjects.SpecialObjects.Pads
{
/// <summary>Represents a red pad.</summary>
[ObjectID(PadType.RedPad)]
public class RedPad : Pad
{
/// <summary>The object ID of the red pad.</summary>
[ObjectStringMappable(ObjectParameter.ID)]
public override int ObjectID => (int)PadType.RedPad;
/// <summary>Initializes a new instance of the <seealso cref="RedPad"/> class.</summary>
public RedPad() : base() { }
/// <summary>Returns a clone of this <seealso cref="RedPad"/>.</summary>
public override GeneralObject Clone() => AddClonedInstanceInformation(new RedPad());
}
}
| 35.428571 | 96 | 0.674731 | [
"MIT"
] | Altenhh/GDAPI | GDAPI/GDAPI/Objects/GeometryDash/LevelObjects/SpecialObjects/Pads/RedPad.cs | 746 | C# |
using System;
using System.Collections.Generic;
namespace FubuMVC.Core.Validation.Fields
{
public class FieldRuleSource : IValidationSource
{
private readonly IFieldRulesRegistry _registry;
public FieldRuleSource(IFieldRulesRegistry registry)
{
_registry = registry;
}
public IEnumerable<IValidationRule> RulesFor(Type type)
{
yield return _registry.RulesFor(type);
}
}
} | 24.25 | 64 | 0.63299 | [
"Apache-2.0"
] | DovetailSoftware/fubumvc | src/FubuMVC.Core/Validation/Fields/FieldRuleSource.cs | 485 | C# |
using RealWorldApp.Models;
using RealWorldApp.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace RealWorldApp.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MoviesListPage : ContentPage
{
public ObservableCollection<MovieList> MoviesCollection;
private int pageNumber = 0;
public MoviesListPage()
{
InitializeComponent();
MoviesCollection = new ObservableCollection<MovieList>();
GetMovies();
}
private async void GetMovies()
{
pageNumber++;
var movies = await ApiService.GetAllMovies(pageNumber, 6);
foreach (var movie in movies)
{
MoviesCollection.Add(movie);
}
CvMovies.ItemsSource = MoviesCollection;
}
private void CvMovies_RemainingItemsThresholdReached(object sender, EventArgs e)
{
GetMovies();
}
private void ImgBack_Tapped(object sender, EventArgs e)
{
Navigation.PopModalAsync();
}
private async void CvMovies_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var currentSelection = e.CurrentSelection.FirstOrDefault() as MovieList;
if (currentSelection == null) return;
var result = await DisplayAlert("Alert", "Do you want to delete this movie", "Yes", "No");
if (result)
{
var response = await ApiService.DeleteMovie(currentSelection.Id);
if (response == false) return;
MoviesCollection.Clear();
pageNumber = 0;
GetMovies();
}
((CollectionView)sender).SelectedItem = null;
}
private void ImgAdd_Tapped(object sender, EventArgs e)
{
Navigation.PushModalAsync(new AddMoviePage());
}
}
} | 30.913043 | 102 | 0.602907 | [
"MIT"
] | codewithasfend/Cinema-App | RealWorldAppForAdmin/RealWorldApp/RealWorldApp/Pages/MoviesListPage.xaml.cs | 2,135 | C# |
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Security.Cryptography.X509Certificates;
namespace Slik.Security
{
/// <summary>
/// Setups client and server certificates for CA signed mode, setups client and server validation to check for them
/// Does not perform chain or revocation checks
/// </summary>
public class CaSignedCertifier : CertifierBase
{
public CaSignedCertifier(IOptions<CertificateOptions> options, ILogger<CaSignedCertifier> logger)
: base(options, logger)
{
if (options.Value.UseSelfSigned)
throw new Exception("Wrong certifier");
if (options.Value.ServerCertificate == null)
throw new ArgumentNullException(nameof(options.Value.ServerCertificate));
}
protected override bool ValidateClientCertificate(X509Certificate2 certificate) =>
certificate.Thumbprint.Equals(Options.ClientCertificate?.Thumbprint);
protected override bool ValidateServerCertificate(X509Certificate2 certificate) =>
certificate.Thumbprint.Equals(Options.ServerCertificate?.Thumbprint);
}
}
| 38.709677 | 119 | 0.711667 | [
"MIT"
] | Insvald/Slik | src/SlikSecurity/CaSignedCertifier.cs | 1,202 | C# |
using System.Linq;
using System.Web.Mvc;
using StackExchange.Opserver.Data.Dashboard;
using StackExchange.Opserver.Helpers;
namespace StackExchange.Opserver.Controllers
{
public partial class DashboardController
{
[OutputCache(Duration = 1, VaryByParam = "node", VaryByContentEncoding = "gzip;deflate")]
[Route("dashboard/node/poll/cpu")]
public ActionResult PollCPU(int? id = null, string node = null, string range = null)
{
var n = id.HasValue ? DashboardData.GetNodeById(id.Value) : DashboardData.GetNodeByName(node);
if (n == null)
return JsonNotFound();
var data = n.GetCPUUtilization();
if (data == null || data.Data == null)
return JsonNotFound();
var total = data.Data.FirstOrDefault(c => c.Name == "Total");
return Json(new
{
duration = data.Duration.TotalMilliseconds,
cores = data.Data.Where(c => c != total).Select(c => new
{
name = c.Name,
utilization = c.Utilization
}),
total = total != null ? total.Utilization : 0
});
}
}
} | 36.027778 | 106 | 0.532768 | [
"MIT"
] | ExclamationLabs/Opserver | Opserver/Controllers/DashboardController.Polling.cs | 1,299 | C# |
using QuieroPizza.BL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace QuieroPizza.Win
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var productosbl = new ProductosBL();
var listadeproductos = productosbl.obtenerProductos();
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
| 19.30303 | 66 | 0.618524 | [
"MIT"
] | cfernandez2021/quieropizza | Quieropizza/QuieroPizza.Win/Form1.cs | 639 | C# |
namespace Kaonavi.Net.Entities;
/// <summary>レイアウト定義 カスタム列項目</summary>
/// <param name="Id">シート項目ID</param>
/// <param name="Name"><inheritdoc cref="FieldLayout" path="/param[@name='Name']"/></param>
/// <param name="Required"><inheritdoc cref="FieldLayout" path="/param[@name='Required']"/></param>
/// <param name="Type"><inheritdoc cref="FieldLayout" path="/param[@name='Type']"/></param>
/// <param name="MaxLength"><inheritdoc cref="FieldLayout" path="/param[@name='MaxLength']"/></param>
/// <param name="Enum"><inheritdoc cref="FieldLayout" path="/param[@name='Enum']"/></param>
public record CustomFieldLayout(
[property: JsonPropertyName("id")] int Id,
string Name,
bool Required,
FieldType Type,
int? MaxLength,
IReadOnlyList<string?> Enum
) : FieldLayout(Name, Required, Type, MaxLength, Enum);
| 46.166667 | 101 | 0.681107 | [
"MIT"
] | nogic1008/Kaonavi.Core | src/Kaonavi.NET/Entities/Layouts/CustomFieldLayout.cs | 869 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CS_ASP_013 {
public partial class Default {
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// firstTextBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox firstTextBox;
/// <summary>
/// comparisonTypeLabel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label comparisonTypeLabel;
/// <summary>
/// secondTextBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox secondTextBox;
/// <summary>
/// checkedCheckBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox checkedCheckBox;
/// <summary>
/// okButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button okButton;
/// <summary>
/// resultLabel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label resultLabel;
}
}
| 34.35443 | 84 | 0.529477 | [
"MIT"
] | DeveloperUniversity/CS-ASP-013 | Lesson-13/After/CS-ASP_013/CS-ASP_013/Default.aspx.designer.cs | 2,716 | C# |
namespace Chatter.CQRS.Commands
{
/// <summary>
/// Marker
/// </summary>
public interface ICommand : IMessage
{
}
}
| 14.2 | 40 | 0.556338 | [
"MIT"
] | brenpike/Chatter | src/Chatter.CQRS/src/Chatter.CQRS/Commands/ICommand.cs | 144 | C# |
#nullable disable
using System;
using System.Linq;
using SpecFlow.VisualStudio.Editor.Completions;
namespace SpecFlow.VisualStudio.Tests.Editor.Completions;
public class StepDefinitionSamplerTests
{
private ProjectStepDefinitionBinding CreateStepDefinitionBinding(string regex, params string[] parameterTypes)
{
parameterTypes = parameterTypes ?? new string[0];
return new ProjectStepDefinitionBinding(ScenarioBlock.Given, new Regex("^" + regex + "$"), null,
new ProjectStepDefinitionImplementation("M1", parameterTypes, null));
}
[Fact]
public void Uses_regex_core_for_simple_stepdefs()
{
var sut = new StepDefinitionSampler();
var result = sut.GetStepDefinitionSample(CreateStepDefinitionBinding("I press add"));
result.Should().Be("I press add");
}
[Theory]
[InlineData("I have entered (.*) into the calculator", "I have entered [int] into the calculator", "System.Int32")]
[InlineData("(.*) is entered into the calculator", "[int] is entered into the calculator", "System.Int32")]
[InlineData("what I have entered into the calculator is (.*)", "what I have entered into the calculator is [int]",
"System.Int32")]
[InlineData("I have entered (.*) into the calculator", "I have entered [string] into the calculator",
"System.String")]
[InlineData("I have entered (.*) into the calculator", "I have entered [Version] into the calculator",
"System.Version")]
[InlineData("I have entered (.*) and (.*) into the calculator",
"I have entered [int] and [???] into the calculator", "System.Int32")]
[InlineData("I have entered (.*) and ([^\"]*) into the calculator",
"I have entered [int] and [string] into the calculator", "System.Int32", "System.String")]
public void Emits_param_placeholders(string regex, string expectedResult, params string[] paramType)
{
var sut = new StepDefinitionSampler();
var result = sut.GetStepDefinitionSample(CreateStepDefinitionBinding(regex, paramType));
result.Should().Be(expectedResult);
}
[Theory]
[InlineData(@"some \(context\)", @"some (context)")]
[InlineData(@"some \{context\}", @"some {context}")]
[InlineData(@"some \[context\]", @"some [context]")]
[InlineData(@"some \[context]", @"some [context]")]
[InlineData(@"some \[context] (.*)", @"some [context] [???]")]
[InlineData(@"chars \\\*\+\?\|\{\}\[\]\(\)\^\$\#", @"chars \*+?|{}[]()^$#")]
public void Unescapes_masked_chars(string regex, string expectedResult)
{
var sut = new StepDefinitionSampler();
var result = sut.GetStepDefinitionSample(CreateStepDefinitionBinding(regex));
result.Should().Be(expectedResult);
}
[Theory]
[InlineData(@"foo (\d+) bar", @"foo [int] bar")]
[InlineData(@"foo (?<hello>.(.)) bar", @"foo [int] bar")]
[InlineData(@"foo (?<hello>.\)(.)) bar", @"foo [int] bar")]
public void Allows_nested_groups(string regex, string expectedResult)
{
var sut = new StepDefinitionSampler();
var result = sut.GetStepDefinitionSample(CreateStepDefinitionBinding(regex, "System.Int32"));
result.Should().Be(expectedResult);
}
[Theory]
[InlineData(@"foo? (\d+) bar")]
[InlineData(@"foo (?:\d+) bar")]
[InlineData(@"foo [a-z] bar")]
[InlineData(@"foo. (\d+) bar")]
[InlineData(@"foo* (\d+) bar")]
[InlineData(@"foo+ (\d+) bar")]
public void Falls_back_to_regex(string regex)
{
var sut = new StepDefinitionSampler();
var result = sut.GetStepDefinitionSample(CreateStepDefinitionBinding(regex, "System.Int32"));
result.Should().Be(regex);
}
}
| 39.670213 | 119 | 0.642532 | [
"MIT"
] | SpecFlowOSS/SpecFlow.VS | Tests/SpecFlow.VisualStudio.Tests/Editor/Completions/StepDefinitionSamplerTests.cs | 3,731 | C# |
using FacilityServices.DataLayer;
using FacilityServices.DataLayer.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OnlineServices.Common.Exceptions;
using OnlineServices.Common.FacilityServices.TransfertObjects;
using OnlineServices.Common.TranslationServices.TransfertObjects;
using System;
using System.Linq;
using System.Reflection;
namespace FacilityServices.DataLayerTests.RepositoriesTests.ComponentTypeRepositoryTests
{
[TestClass]
public class UpdateComponentTypesTests
{
[TestMethod]
public void UpdateComponentTypeByTransfertObject_Successfull()
{
var options = new DbContextOptionsBuilder<FacilityContext>()
.UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name)
.Options;
using (var memoryCtx = new FacilityContext(options))
{
var ComponentTypeToUseInTest = new ComponentTypeTO
{
Archived = false,
Name = new MultiLanguageString("Name1En", "Name1Fr", "Name1Nl"),
};
var ComponentTypeToUseInTest2 = new ComponentTypeTO
{
Archived = false,
Name = new MultiLanguageString("Name2En", "Name2Fr", "Name2Nl"),
};
var componentTypeRepository = new ComponentTypeRepository(memoryCtx);
var f1 = componentTypeRepository.Add(ComponentTypeToUseInTest);
var f2 = componentTypeRepository.Add(ComponentTypeToUseInTest2);
memoryCtx.SaveChanges();
f2.Name.French = "UpdatedFrenchName";
f2.Archived = true;
componentTypeRepository.Update(f2);
Assert.AreEqual(2, componentTypeRepository.GetAll().Count());
Assert.AreEqual("UpdatedFrenchName", f2.Name.French);
Assert.AreEqual(true, f2.Archived);
}
}
[TestMethod]
public void UpdateComponentTypeByTransfertObject_ThrowException_WhenNullIsSupplied()
{
var options = new DbContextOptionsBuilder<FacilityContext>()
.UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name)
.Options;
using (var memoryCtx = new FacilityContext(options))
{
var componentTypeRepository = new ComponentTypeRepository(memoryCtx);
Assert.ThrowsException<ArgumentNullException>(() => componentTypeRepository.Update(null));
}
}
[TestMethod]
public void UpdateComponentTypeByTransfertObject_ThrowException_WhenUnexistingComponentTypeIsSupplied()
{
var options = new DbContextOptionsBuilder<FacilityContext>()
.UseInMemoryDatabase(databaseName: MethodBase.GetCurrentMethod().Name)
.Options;
using (var memoryCtx = new FacilityContext(options))
{
var componentTypeRepository = new ComponentTypeRepository(memoryCtx);
var componentTypeTO = new ComponentTypeTO { Id = 999 };
Assert.ThrowsException<LoggedException>(() => componentTypeRepository.Update(componentTypeTO));
}
}
}
}
| 41.134146 | 111 | 0.635636 | [
"Apache-2.0"
] | EnriqueUbillus/OnlineServices | Application Layer/FacilityServices/FacilityServices.DataLayerTests/RepositoriesTests/ComponentTypeRepositoryTests/ComponentType - UpdateComponentTypesTests.cs | 3,375 | C# |
//
// DomElement.cs
//
// Author: Kees van Spelde <[email protected]>
//
// Copyright (c) 2013-2019 Magic-Sessions. (www.magic-sessions.com)
//
// 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 NON INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Text;
namespace MsgReader.Rtf
{
/// <summary>
/// RTF dom element (this is the most base element type)
/// </summary>
internal abstract class DomElement
{
#region Fields
/// <summary>
/// Native level in RTF document
/// </summary>
internal int NativeLevel = -1;
private DomDocument _ownerDocument;
#endregion
#region Properties
/// <summary>
/// RTF native attribute
/// </summary>
public AttributeList Attributes { get; set; }
/// <summary>
/// child elements list
/// </summary>
public DomElementList Elements { get; }
/// <summary>
/// The document which owned this element
/// </summary>
public DomDocument OwnerDocument
{
get { return _ownerDocument; }
set
{
_ownerDocument = value;
foreach (DomElement element in Elements)
{
element.OwnerDocument = value;
}
}
}
/// <summary>
/// Parent element
/// </summary>
public DomElement Parent { get; private set; }
public virtual string InnerText
{
get
{
var stringBuilder = new StringBuilder();
if (Elements != null)
{
foreach (DomElement element in Elements)
{
stringBuilder.Append(element.InnerText);
}
}
return stringBuilder.ToString();
}
}
/// <summary>
/// Whether element is locked , if element is lock , it can not append chidl element
/// </summary>
public bool Locked { get; set; }
#endregion
#region Protected constructor
protected DomElement()
{
Elements = new DomElementList();
Attributes = new AttributeList();
}
#endregion
#region HasAttribute
public bool HasAttribute(string name)
{
return Attributes.Contains(name);
}
#endregion
#region GetAttributeValue
public int GetAttributeValue(string name, int defaultValue)
{
return Attributes.Contains(name) ? Attributes[name] : defaultValue;
}
#endregion
#region AppendChild
/// <summary>
/// Append child element
/// </summary>
/// <param name="element">child element</param>
/// <returns>index of element</returns>
public int AppendChild(DomElement element)
{
CheckLocked();
element.Parent = this;
element.OwnerDocument = _ownerDocument;
return Elements.Add(element);
}
#endregion
#region SetAttribute
/// <summary>
/// Set attribute
/// </summary>
/// <param name="name">name</param>
/// <param name="value">value</param>
public void SetAttribute(string name, int value)
{
CheckLocked();
Attributes[name] = value;
}
#endregion
#region CheckLocked
private void CheckLocked()
{
if (Locked)
{
throw new InvalidOperationException("Element locked");
}
}
#endregion
#region SetLockedDeeply
public void SetLockedDeeply(bool locked)
{
Locked = locked;
if (Elements != null)
{
foreach (DomElement element in Elements)
{
element.SetLockedDeeply(locked);
}
}
}
#endregion
#region ToDomString
public virtual string ToDomString()
{
var stringBuilder = new StringBuilder();
stringBuilder.Append(ToString());
ToDomString(Elements, stringBuilder, 1);
return stringBuilder.ToString();
}
protected void ToDomString(DomElementList elements, StringBuilder stringBuilder, int level)
{
foreach (DomElement element in elements)
{
stringBuilder.Append(Environment.NewLine);
stringBuilder.Append(new string(' ', level*4));
stringBuilder.Append(element);
ToDomString(element.Elements, stringBuilder, level + 1);
}
}
#endregion
}
} | 29.969388 | 99 | 0.55618 | [
"MIT"
] | Argus-Media/MSGReader | MsgReaderCore/Rtf/DomElement.cs | 5,874 | C# |
using System;
namespace Standard
{
internal struct RGBQUAD
{
public byte rgbBlue;
public byte rgbGreen;
public byte rgbRed;
public byte rgbReserved;
}
}
| 12.625 | 32 | 0.59901 | [
"MIT"
] | 5653325/HandyControl | src/Shared/Microsoft.Windows.Shell/Standard/RGBQUAD.cs | 204 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Identity.Views.Manage
{
public static class ManageNavPages
{
public static string ActivePageKey => "ActivePage";
public static string Index => "Index";
public static string ChangePassword => "ChangePassword";
public static string ExternalLogins => "ExternalLogins";
public static string TwoFactorAuthentication => "TwoFactorAuthentication";
public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index);
public static string ChangePasswordNavClass(ViewContext viewContext) => PageNavClass(viewContext, ChangePassword);
public static string ExternalLoginsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ExternalLogins);
public static string TwoFactorAuthenticationNavClass(ViewContext viewContext) => PageNavClass(viewContext, TwoFactorAuthentication);
public static string PageNavClass(ViewContext viewContext, string page)
{
var activePage = viewContext.ViewData["ActivePage"] as string;
return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null;
}
public static void AddActivePage(this ViewDataDictionary viewData, string activePage) => viewData[ActivePageKey] = activePage;
}
}
| 38.846154 | 140 | 0.744554 | [
"MIT"
] | mohamedelmesawy1993/BIMgo-GP | BIMGo-WebSite/Identity/Views/Manage/ManageNavPages.cs | 1,517 | 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 auditmanager-2017-07-25.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.AuditManager.Model
{
/// <summary>
/// The file used to structure and automate AWS Audit Manager assessments for a given
/// compliance standard.
/// </summary>
public partial class Framework
{
private string _arn;
private string _complianceType;
private List<ControlSet> _controlSets = new List<ControlSet>();
private string _controlSources;
private DateTime? _createdAt;
private string _createdBy;
private string _description;
private string _id;
private DateTime? _lastUpdatedAt;
private string _lastUpdatedBy;
private string _logo;
private string _name;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
private FrameworkType _type;
/// <summary>
/// Gets and sets the property Arn.
/// <para>
/// The Amazon Resource Name (ARN) of the specified framework.
/// </para>
/// </summary>
[AWSProperty(Min=20, Max=2048)]
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property ComplianceType.
/// <para>
/// The compliance type that the new custom framework supports, such as CIS or HIPAA.
///
/// </para>
/// </summary>
[AWSProperty(Max=100)]
public string ComplianceType
{
get { return this._complianceType; }
set { this._complianceType = value; }
}
// Check to see if ComplianceType property is set
internal bool IsSetComplianceType()
{
return this._complianceType != null;
}
/// <summary>
/// Gets and sets the property ControlSets.
/// <para>
/// The control sets associated with the framework.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public List<ControlSet> ControlSets
{
get { return this._controlSets; }
set { this._controlSets = value; }
}
// Check to see if ControlSets property is set
internal bool IsSetControlSets()
{
return this._controlSets != null && this._controlSets.Count > 0;
}
/// <summary>
/// Gets and sets the property ControlSources.
/// <para>
/// The sources from which AWS Audit Manager collects evidence for the control.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=100)]
public string ControlSources
{
get { return this._controlSources; }
set { this._controlSources = value; }
}
// Check to see if ControlSources property is set
internal bool IsSetControlSources()
{
return this._controlSources != null;
}
/// <summary>
/// Gets and sets the property CreatedAt.
/// <para>
/// Specifies when the framework was created.
/// </para>
/// </summary>
public DateTime CreatedAt
{
get { return this._createdAt.GetValueOrDefault(); }
set { this._createdAt = value; }
}
// Check to see if CreatedAt property is set
internal bool IsSetCreatedAt()
{
return this._createdAt.HasValue;
}
/// <summary>
/// Gets and sets the property CreatedBy.
/// <para>
/// The IAM user or role that created the framework.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=100)]
public string CreatedBy
{
get { return this._createdBy; }
set { this._createdBy = value; }
}
// Check to see if CreatedBy property is set
internal bool IsSetCreatedBy()
{
return this._createdBy != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the specified framework.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1000)]
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 Id.
/// <para>
/// The unique identifier for the specified framework.
/// </para>
/// </summary>
[AWSProperty(Min=36, Max=36)]
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property LastUpdatedAt.
/// <para>
/// Specifies when the framework was most recently updated.
/// </para>
/// </summary>
public DateTime LastUpdatedAt
{
get { return this._lastUpdatedAt.GetValueOrDefault(); }
set { this._lastUpdatedAt = value; }
}
// Check to see if LastUpdatedAt property is set
internal bool IsSetLastUpdatedAt()
{
return this._lastUpdatedAt.HasValue;
}
/// <summary>
/// Gets and sets the property LastUpdatedBy.
/// <para>
/// The IAM user or role that most recently updated the framework.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=100)]
public string LastUpdatedBy
{
get { return this._lastUpdatedBy; }
set { this._lastUpdatedBy = value; }
}
// Check to see if LastUpdatedBy property is set
internal bool IsSetLastUpdatedBy()
{
return this._lastUpdatedBy != null;
}
/// <summary>
/// Gets and sets the property Logo.
/// <para>
/// The logo associated with the framework.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=255)]
public string Logo
{
get { return this._logo; }
set { this._logo = value; }
}
// Check to see if Logo property is set
internal bool IsSetLogo()
{
return this._logo != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the specified framework.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=300)]
public string 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 Tags.
/// <para>
/// The tags associated with the framework.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=50)]
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The framework type, such as custom or standard.
/// </para>
/// </summary>
public FrameworkType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
}
} | 29.018927 | 110 | 0.533971 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/AuditManager/Generated/Model/Framework.cs | 9,199 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DM.MovieApi.ApiResponse;
using DM.MovieApi.IntegrationTests.Infrastructure;
using DM.MovieApi.MovieDb;
using DM.MovieApi.MovieDb.Companies;
using DM.MovieApi.MovieDb.Genres;
using DM.MovieApi.MovieDb.Keywords;
using DM.MovieApi.MovieDb.Movies;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DM.MovieApi.IntegrationTests.MovieDb.Movies
{
[TestClass]
public class ApiMovieRequestTests
{
private IApiMovieRequest _api;
[TestInitialize]
public void TestInit()
{
ApiResponseUtil.ThrottleTests();
_api = MovieDbFactory.Create<IApiMovieRequest>().Value;
Assert.IsInstanceOfType( _api, typeof( ApiMovieRequest ) );
}
[TestMethod]
public async Task SearchByTitleAsync_Excludes_AdultFilms()
{
// 2 parts to test:
// 1. manual search to verify adult films
// 2. api search to verify no adult films
const string adultFilmTitle = "Debbie Does Dallas";
var param = new Dictionary<string, string>
{
{"query", adultFilmTitle},
{"include_adult", "true"},
{"language", "en"},
};
string[] expectedAdultTitles =
{
"Debbie Does Dallas",
"Debbie Does Dallas... Again",
"Debbie Does Dallas: The Revenge",
"Debbie Does Dallas Part II",
"Debbie Does Dallas III: The Final Chapter",
};
var integrationApi = new IntegrationApiRequest( AssemblyInit.Settings );
var adult = await integrationApi.SearchAsync<MovieInfo>( "search/movie", param );
foreach( string title in expectedAdultTitles )
{
var adultMovie = adult.Results.SingleOrDefault( x => x.Title == title );
Assert.IsNotNull( adultMovie );
}
ApiSearchResponse<MovieInfo> search = await _api.SearchByTitleAsync( adultFilmTitle );
// if any results are returned, ensure they are not marked as an adult film
foreach( MovieInfo movie in search.Results )
{
Assert.IsFalse( movie.IsAdultThemed );
}
}
[TestMethod]
public async Task SearchByTitleAsync_RunLolaRun_Returns_SingleResult_WithExpectedValues()
{
const string runLolaRun = "Run Lola Run";
ApiSearchResponse<MovieInfo> response = await _api.SearchByTitleAsync( runLolaRun );
AssertRunLolaRun( response, runLolaRun );
}
[TestMethod]
public async Task SearchByTitleAsync_RunLolaRun_Returns_SingleResult_WithExpectedValues_InGerman()
{
const string runLolaRun = "Run Lola Run";
const string expectedTitle = "Lola rennt";
ApiSearchResponse<MovieInfo> response = await _api.SearchByTitleAsync( runLolaRun, 1, "de" );
AssertRunLolaRun( response, expectedTitle );
}
private void AssertRunLolaRun( ApiSearchResponse<MovieInfo> response, string expectedTitle )
{
ApiResponseUtil.AssertErrorIsNull( response );
Assert.AreEqual( 1, response.TotalResults );
Assert.AreEqual( 1, response.Results.Count );
MovieInfo movie = response.Results.Single();
Assert.AreEqual( 104, movie.Id );
Assert.AreEqual( expectedTitle, movie.Title );
Assert.AreEqual( new DateTime( 1998, 08, 20 ), movie.ReleaseDate );
var expectedGenres = new List<Genre>
{
GenreFactory.Action(),
GenreFactory.Drama(),
GenreFactory.Thriller(),
};
CollectionAssert.AreEquivalent( expectedGenres, movie.Genres.ToArray() );
}
[TestMethod]
public async Task SearchByTitleAsync_CanPageResults()
{
const string query = "Harry";
const int minimumPageCount = 8;
const int minimumTotalResultsCount = 140;
await ApiResponseUtil.AssertCanPageSearchResponse( query, minimumPageCount, minimumTotalResultsCount,
( search, pageNumber ) => _api.SearchByTitleAsync( search, pageNumber ), x => x.Id );
}
[TestMethod]
public async Task FindByIdAsync_StarWarsTheForceAwakens_Returns_AllValues()
{
const int id = 140607;
const string expectedImdbId = "tt2488496";
const string expectedTitle = "Star Wars: The Force Awakens";
const string expectedOriginalTitle = "Star Wars: The Force Awakens";
const string expectedTagline = "Every generation has a story.";
const string expectedOverview = "Thirty years after defeating the Galactic Empire"; // truncated
const string expectedOriginalLanguage = "en";
const string expectedHomepage = "http://www.starwars.com/films/star-wars-episode-vii";
const string expectedStatus = "Released";
const int expectedBudget = 245000000;
const int expectedRuntime = 136;
var expectedReleaseDate = new DateTime( 2015, 12, 15 );
ApiQueryResponse<Movie> response = await _api.FindByIdAsync( id );
ApiResponseUtil.AssertErrorIsNull( response );
Movie movie = response.Item;
Assert.AreEqual( id, movie.Id );
Assert.AreEqual( expectedImdbId, movie.ImdbId );
Assert.AreEqual( expectedTitle, movie.Title );
Assert.AreEqual( expectedOriginalTitle, movie.OriginalTitle );
Assert.AreEqual( expectedTagline, movie.Tagline );
Assert.AreEqual( expectedOriginalLanguage, movie.OriginalLanguage );
Assert.AreEqual( expectedHomepage, movie.Homepage );
Assert.AreEqual( expectedStatus, movie.Status );
Assert.AreEqual( expectedBudget, movie.Budget );
Assert.AreEqual( expectedRuntime, movie.Runtime );
Assert.AreEqual( expectedReleaseDate, movie.ReleaseDate );
ApiResponseUtil.AssertImagePath( movie.BackdropPath );
ApiResponseUtil.AssertImagePath( movie.PosterPath );
Assert.IsTrue( movie.Overview.StartsWith( expectedOverview ) );
Assert.IsTrue( movie.Popularity > 7, $"Actual: {movie.Popularity}" );
Assert.IsTrue( movie.VoteAverage > 5 );
Assert.IsTrue( movie.VoteCount > 1500 );
// Spoken Languages
var languages = new[]
{
new Language("en", "English"),
};
CollectionAssert.AreEqual( languages, movie.SpokenLanguages.ToArray() );
// Production Companies
var companies = new[]
{
new ProductionCompanyInfo(1, "Lucasfilm Ltd."),
new ProductionCompanyInfo(1634, "Truenorth Productions"),
new ProductionCompanyInfo(11461, "Bad Robot"),
};
CollectionAssert.AreEquivalent( companies, movie.ProductionCompanies.ToArray(),
"actual:\r\n" + string.Join( "\r\n", movie.ProductionCompanies ) );
// Production Countries
var countries = new[]
{
new Country("US", "United States of America"),
};
CollectionAssert.AreEqual( countries, movie.ProductionCountries.ToArray() );
// Movie Collection
Assert.IsNotNull( movie.MovieCollectionInfo );
Assert.AreEqual( 10, movie.MovieCollectionInfo.Id );
Assert.AreEqual( "Star Wars Collection", movie.MovieCollectionInfo.Name );
ApiResponseUtil.AssertImagePath( movie.MovieCollectionInfo.BackdropPath );
ApiResponseUtil.AssertImagePath( movie.MovieCollectionInfo.PosterPath );
// Genres
var expectedGenres = new List<Genre>
{
GenreFactory.Action(),
GenreFactory.Adventure(),
GenreFactory.ScienceFiction(),
GenreFactory.Fantasy(),
};
CollectionAssert.AreEquivalent( expectedGenres, movie.Genres.ToArray(),
"actual:\r\n" + string.Join( "\r\n", movie.Genres ) );
// Keywords
var expectedKeywords = new List<Keyword>
{
new Keyword(803, "android"),
new Keyword(1612, "spacecraft"),
new Keyword(10527, "jedi"),
new Keyword(161176, "space opera"),
new Keyword(156395, "imax"),
};
CollectionAssert.AreEquivalent( expectedKeywords, movie.Keywords.ToArray(),
"actual:\r\n" + string.Join( "\r\n", movie.Keywords ) );
}
[TestMethod]
public async Task FindByIdAsync_Returns_German_With_LanguageParameter()
{
const int id = 140607;
const string language = "de";
const string expectedTitle = "Star Wars: Das Erwachen der Macht";
ApiQueryResponse<Movie> response = await _api.FindByIdAsync( id, language );
ApiResponseUtil.AssertErrorIsNull( response );
Assert.AreEqual( id, response.Item.Id );
Assert.AreEqual( expectedTitle, response.Item.Title );
}
[TestMethod]
public async Task MovieWithLargeRevenue_Will_Deserialize()
{
const int id = 19995;
const string expectedTitle = "Avatar";
ApiQueryResponse<Movie> response = await _api.FindByIdAsync( id );
ApiResponseUtil.AssertErrorIsNull( response );
Assert.AreEqual( expectedTitle, response.Item.Title );
Assert.IsTrue( response.Item.Revenue > int.MaxValue );
}
[TestMethod]
public async Task GetLatestAsync_Returns_ValidResult()
{
ApiQueryResponse<Movie> response = await _api.GetLatestAsync();
ApiResponseUtil.AssertErrorIsNull( response );
ApiResponseUtil.AssertMovieStructure( response.Item );
}
[TestMethod]
public async Task GetNowPlayingAsync_Returns_ValidResults()
{
ApiSearchResponse<Movie> response = await _api.GetNowPlayingAsync();
ApiResponseUtil.AssertErrorIsNull( response );
ApiResponseUtil.AssertMovieStructure( response.Results );
}
[TestMethod]
public async Task GetNowPlayingAsync_CanPageResults()
{
// Now Playing typically has 25+ pages.
const int minimumPageCount = 5;
const int minimumTotalResultsCount = 100; // 20 results per page x 5 pages = 100
await ApiResponseUtil.AssertCanPageSearchResponse( "unused", minimumPageCount, minimumTotalResultsCount,
( str, page ) => _api.GetNowPlayingAsync( page ), x => x.Id );
}
[TestMethod]
public async Task GetUpcomingAsync_Returns_ValidResults()
{
ApiSearchResponse<Movie> response = await _api.GetUpcomingAsync();
ApiResponseUtil.AssertErrorIsNull( response );
ApiResponseUtil.AssertMovieStructure( response.Results );
}
[TestMethod]
public async Task GetUpcomingAsync_CanPageResults()
{
// Now Playing typically has 5+ pages.
// - intentionally setting minimumTotalResultsCount at 50; sometimes upcoming movies are scarce.
const int minimumPageCount = 3;
const int minimumTotalResultsCount = 50; // 20 results per page x 3 pages = 60
await ApiResponseUtil.AssertCanPageSearchResponse( "unused", minimumPageCount, minimumTotalResultsCount,
( str, page ) => _api.GetUpcomingAsync( page ), x => x.Id );
}
[TestMethod]
public async Task GetTopRatedAsync_Returns_ValidResults()
{
ApiSearchResponse<MovieInfo> response = await _api.GetTopRatedAsync();
ApiResponseUtil.AssertErrorIsNull( response );
IReadOnlyList<MovieInfo> results = response.Results;
ApiResponseUtil.AssertMovieInformationStructure( results );
}
[TestMethod]
public async Task GetTopRatedAsync_CanPageResults()
{
const int minimumPageCount = 2;
const int minimumTotalResultsCount = 40;
await ApiResponseUtil.AssertCanPageSearchResponse( "unused", minimumPageCount, minimumTotalResultsCount,
( str, page ) => _api.GetTopRatedAsync( page ), x => x.Id );
}
[TestMethod]
public async Task GetPopularAsync_Returns_ValidResults()
{
ApiSearchResponse<MovieInfo> response = await _api.GetPopularAsync();
ApiResponseUtil.AssertErrorIsNull( response );
IReadOnlyList<MovieInfo> results = response.Results;
ApiResponseUtil.AssertMovieInformationStructure( results );
}
[TestMethod]
public async Task GetPopularAsync_CanPageResults()
{
const int minimumPageCount = 2;
const int minimumTotalResultsCount = 40;
await ApiResponseUtil.AssertCanPageSearchResponse( "unused", minimumPageCount, minimumTotalResultsCount,
( str, page ) => _api.GetPopularAsync( page ), x => x.Id );
}
}
}
| 38.157303 | 116 | 0.612264 | [
"MIT"
] | ericleroy01/TheMovieDbWrapper | DM.MovieApi.IntegrationTests/MovieDb/Movies/ApiMovieRequestTests.cs | 13,586 | C# |
using System;
namespace MobaFrame.SkillAction
{
public enum BombType
{
None,
PenetratingBomb,
ColliderBomb
}
}
| 11 | 32 | 0.674242 | [
"MIT"
] | corefan/mobahero_src | MobaFrame.SkillAction/BombType.cs | 132 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SwitchDemo.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SwitchDemo.iOS")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("72bdc44f-c588-44f3-b6df-9aace7daafdd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.864865 | 84 | 0.744468 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter15/SwitchDemo/SwitchDemo/SwitchDemo.iOS/Properties/AssemblyInfo.cs | 1,404 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZumenSearch.Models
{
/// <summary>
/// 情報保持・表示用のMyErrorクラス
/// </summary>
#region == エラー情報保持・表示用クラス ==
public class ErrorObject
{
public enum ErrTypes
{
DB, API, Other
};
public ErrTypes ErrType { get; set; } // eg "API, DB, other"
public int ErrCode { get; set; } // HTTP ERROR CODE?
public string ErrText { get; set; } // API error code translated via dictionaly.
public string ErrPlace { get; set; } // eg RESTのPATH。
public string ErrPlaceParent { get; set; } // ?
public DateTime ErrDatetime { get; set; }
public string ErrDescription { get; set; } // 自前の補足説明。
}
public class ResultWrapper
{
public ErrorObject Error;
public bool IsError = false;
public Object Data;
public ResultWrapper()
{
Error = new ErrorObject();
}
}
#endregion
}
| 22.354167 | 88 | 0.583411 | [
"MIT"
] | torum/ZumenSearch | ZumenSearch/Models/Error.cs | 1,147 | C# |
using System;
using System.IO;
using Bender.Configuration;
namespace WebApi.Bender
{
public class BenderJsonFormatter : BenderFormatter
{
public BenderJsonFormatter(Options options) :
base(options, "application/json") { }
protected override void Serialize(object value, Stream writeStream, Options options)
{
global::Bender.Serialize.JsonStream(value, writeStream, options);
}
protected override object Deserialize(Stream readStream, Type type, Options options)
{
return global::Bender.Deserialize.Json(readStream, type, options);
}
}
}
| 29 | 93 | 0.646177 | [
"MIT"
] | mikeobrien/WebAPI.Bender | src/WebApi.Bender/BenderJsonFormatter.cs | 669 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Insma.Mxa.Framework.Content.Pipeline.FBXImporter
{
public class Class1
{
}
}
| 15.583333 | 58 | 0.743316 | [
"MIT"
] | baszalmstra/MXA | MXA-Framework/src/Content/Pipeline.FBXImporter/Class1.cs | 189 | C# |
/*
* Copyright 2010-2014 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 sts-2011-06-15.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.SecurityToken.Model
{
/// <summary>
/// Container for the parameters to the AssumeRoleWithSAML operation.
/// Returns a set of temporary security credentials for users who have been authenticated
/// via a SAML authentication response. This operation provides a mechanism for tying
/// an enterprise identity store or directory to role-based AWS access without user-specific
/// credentials or configuration. For a comparison of <code>AssumeRoleWithSAML</code>
/// with the other API operations that produce temporary credentials, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html">Requesting
/// Temporary Security Credentials</a> and <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison">Comparing
/// the AWS STS API operations</a> in the <i>IAM User Guide</i>.
///
///
/// <para>
/// The temporary security credentials returned by this operation consist of an access
/// key ID, a secret access key, and a security token. Applications can use these temporary
/// security credentials to sign calls to AWS services.
/// </para>
///
/// <para>
/// <b>Session Duration</b>
/// </para>
///
/// <para>
/// By default, the temporary security credentials created by <code>AssumeRoleWithSAML</code>
/// last for one hour. However, you can use the optional <code>DurationSeconds</code>
/// parameter to specify the duration of your session. Your role session lasts for the
/// duration that you specify, or until the time specified in the SAML authentication
/// response's <code>SessionNotOnOrAfter</code> value, whichever is shorter. You can provide
/// a <code>DurationSeconds</code> value from 900 seconds (15 minutes) up to the maximum
/// session duration setting for the role. This setting can have a value from 1 hour to
/// 12 hours. To learn how to view the maximum value for your role, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session">View
/// the Maximum Session Duration Setting for a Role</a> in the <i>IAM User Guide</i>.
/// The maximum session duration limit applies when you use the <code>AssumeRole*</code>
/// API operations or the <code>assume-role*</code> CLI commands. However the limit does
/// not apply when you use those operations to create a console URL. For more information,
/// see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html">Using
/// IAM Roles</a> in the <i>IAM User Guide</i>.
/// </para>
///
/// <para>
/// <b>Permissions</b>
/// </para>
///
/// <para>
/// The temporary security credentials created by <code>AssumeRoleWithSAML</code> can
/// be used to make API calls to any AWS service with the following exception: you cannot
/// call the STS <code>GetFederationToken</code> or <code>GetSessionToken</code> API operations.
/// </para>
///
/// <para>
/// (Optional) You can pass inline or managed <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session">session
/// policies</a> to this operation. You can pass a single JSON policy document to use
/// as an inline session policy. You can also specify up to 10 managed policies to use
/// as managed session policies. The plain text that you use for both inline and managed
/// session policies can't exceed 2,048 characters. Passing policies to this operation
/// returns new temporary credentials. The resulting session's permissions are the intersection
/// of the role's identity-based policy and the session policies. You can use the role's
/// temporary credentials in subsequent AWS API calls to access resources in the account
/// that owns the role. You cannot use session policies to grant more permissions than
/// those allowed by the identity-based policy of the role that is being assumed. For
/// more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session">Session
/// Policies</a> in the <i>IAM User Guide</i>.
/// </para>
///
/// <para>
/// Calling <code>AssumeRoleWithSAML</code> does not require the use of AWS security credentials.
/// The identity of the caller is validated by using keys in the metadata document that
/// is uploaded for the SAML provider entity for your identity provider.
/// </para>
/// <important>
/// <para>
/// Calling <code>AssumeRoleWithSAML</code> can result in an entry in your AWS CloudTrail
/// logs. The entry includes the value in the <code>NameID</code> element of the SAML
/// assertion. We recommend that you use a <code>NameIDType</code> that is not associated
/// with any personally identifiable information (PII). For example, you could instead
/// use the persistent identifier (<code>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</code>).
/// </para>
/// </important>
/// <para>
/// <b>Tags</b>
/// </para>
///
/// <para>
/// (Optional) You can configure your IdP to pass attributes into your SAML assertion
/// as session tags. Each session tag consists of a key name and an associated value.
/// For more information about session tags, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html">Passing
/// Session Tags in STS</a> in the <i>IAM User Guide</i>.
/// </para>
///
/// <para>
/// You can pass up to 50 session tags. The plain text session tag keys can’t exceed 128
/// characters and the values can’t exceed 256 characters. For these and additional limits,
/// see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length">IAM
/// and STS Character Limits</a> in the <i>IAM User Guide</i>.
/// </para>
/// <note>
/// <para>
/// An AWS conversion compresses the passed session policies and session tags into a packed
/// binary format that has a separate limit. Your request can fail for this limit even
/// if your plain text meets the other requirements. The <code>PackedPolicySize</code>
/// response element indicates by percentage how close the policies and tags for your
/// request are to the upper size limit.
/// </para>
/// </note>
/// <para>
/// You can pass a session tag with the same key as a tag that is attached to the role.
/// When you do, session tags override the role's tags with the same key.
/// </para>
///
/// <para>
/// An administrator must grant you the permissions necessary to pass session tags. The
/// administrator can also create granular permissions to allow you to pass only specific
/// session tags. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html">Tutorial:
/// Using Tags for Attribute-Based Access Control</a> in the <i>IAM User Guide</i>.
/// </para>
///
/// <para>
/// You can set the session tags as transitive. Transitive tags persist during role chaining.
/// For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining">Chaining
/// Roles with Session Tags</a> in the <i>IAM User Guide</i>.
/// </para>
///
/// <para>
/// <b>SAML Configuration</b>
/// </para>
///
/// <para>
/// Before your application can call <code>AssumeRoleWithSAML</code>, you must configure
/// your SAML identity provider (IdP) to issue the claims required by AWS. Additionally,
/// you must use AWS Identity and Access Management (IAM) to create a SAML provider entity
/// in your AWS account that represents your identity provider. You must also create an
/// IAM role that specifies this SAML provider in its trust policy.
/// </para>
///
/// <para>
/// For more information, see the following resources:
/// </para>
/// <ul> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html">About
/// SAML 2.0-based Federation</a> in the <i>IAM User Guide</i>.
/// </para>
/// </li> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html">Creating
/// SAML Identity Providers</a> in the <i>IAM User Guide</i>.
/// </para>
/// </li> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html">Configuring
/// a Relying Party and Claims</a> in the <i>IAM User Guide</i>.
/// </para>
/// </li> <li>
/// <para>
/// <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html">Creating
/// a Role for SAML 2.0 Federation</a> in the <i>IAM User Guide</i>.
/// </para>
/// </li> </ul>
/// </summary>
public partial class AssumeRoleWithSAMLRequest : AmazonSecurityTokenServiceRequest
{
private int? _durationSeconds;
private string _policy;
private List<PolicyDescriptorType> _policyArns = new List<PolicyDescriptorType>();
private string _principalArn;
private string _roleArn;
private string _samlAssertion;
/// <summary>
/// Gets and sets the property DurationSeconds.
/// <para>
/// The duration, in seconds, of the role session. Your role session lasts for the duration
/// that you specify for the <code>DurationSeconds</code> parameter, or until the time
/// specified in the SAML authentication response's <code>SessionNotOnOrAfter</code> value,
/// whichever is shorter. You can provide a <code>DurationSeconds</code> value from 900
/// seconds (15 minutes) up to the maximum session duration setting for the role. This
/// setting can have a value from 1 hour to 12 hours. If you specify a value higher than
/// this setting, the operation fails. For example, if you specify a session duration
/// of 12 hours, but your administrator set the maximum session duration to 6 hours, your
/// operation fails. To learn how to view the maximum value for your role, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session">View
/// the Maximum Session Duration Setting for a Role</a> in the <i>IAM User Guide</i>.
/// </para>
///
/// <para>
/// By default, the value is set to <code>3600</code> seconds.
/// </para>
/// <note>
/// <para>
/// The <code>DurationSeconds</code> parameter is separate from the duration of a console
/// session that you might request using the returned credentials. The request to the
/// federation endpoint for a console sign-in token takes a <code>SessionDuration</code>
/// parameter that specifies the maximum length of the console session. For more information,
/// see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html">Creating
/// a URL that Enables Federated Users to Access the AWS Management Console</a> in the
/// <i>IAM User Guide</i>.
/// </para>
/// </note>
/// </summary>
[AWSProperty(Min=900, Max=43200)]
public int DurationSeconds
{
get { return this._durationSeconds.GetValueOrDefault(); }
set { this._durationSeconds = value; }
}
// Check to see if DurationSeconds property is set
internal bool IsSetDurationSeconds()
{
return this._durationSeconds.HasValue;
}
/// <summary>
/// Gets and sets the property Policy.
/// <para>
/// An IAM policy in JSON format that you want to use as an inline session policy.
/// </para>
///
/// <para>
/// This parameter is optional. Passing policies to this operation returns new temporary
/// credentials. The resulting session's permissions are the intersection of the role's
/// identity-based policy and the session policies. You can use the role's temporary credentials
/// in subsequent AWS API calls to access resources in the account that owns the role.
/// You cannot use session policies to grant more permissions than those allowed by the
/// identity-based policy of the role that is being assumed. For more information, see
/// <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session">Session
/// Policies</a> in the <i>IAM User Guide</i>.
/// </para>
///
/// <para>
/// The plain text that you use for both inline and managed session policies can't exceed
/// 2,048 characters. The JSON policy characters can be any ASCII character from the space
/// character to the end of the valid character list (\u0020 through \u00FF). It can also
/// include the tab (\u0009), linefeed (\u000A), and carriage return (\u000D) characters.
/// </para>
/// <note>
/// <para>
/// An AWS conversion compresses the passed session policies and session tags into a packed
/// binary format that has a separate limit. Your request can fail for this limit even
/// if your plain text meets the other requirements. The <code>PackedPolicySize</code>
/// response element indicates by percentage how close the policies and tags for your
/// request are to the upper size limit.
/// </para>
/// </note>
/// </summary>
[AWSProperty(Min=1, Max=2048)]
public string Policy
{
get { return this._policy; }
set { this._policy = value; }
}
// Check to see if Policy property is set
internal bool IsSetPolicy()
{
return this._policy != null;
}
/// <summary>
/// Gets and sets the property PolicyArns.
/// <para>
/// The Amazon Resource Names (ARNs) of the IAM managed policies that you want to use
/// as managed session policies. The policies must exist in the same account as the role.
/// </para>
///
/// <para>
/// This parameter is optional. You can provide up to 10 managed policy ARNs. However,
/// the plain text that you use for both inline and managed session policies can't exceed
/// 2,048 characters. For more information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon
/// Resource Names (ARNs) and AWS Service Namespaces</a> in the AWS General Reference.
/// </para>
/// <note>
/// <para>
/// An AWS conversion compresses the passed session policies and session tags into a packed
/// binary format that has a separate limit. Your request can fail for this limit even
/// if your plain text meets the other requirements. The <code>PackedPolicySize</code>
/// response element indicates by percentage how close the policies and tags for your
/// request are to the upper size limit.
/// </para>
/// </note>
/// <para>
/// Passing policies to this operation returns new temporary credentials. The resulting
/// session's permissions are the intersection of the role's identity-based policy and
/// the session policies. You can use the role's temporary credentials in subsequent AWS
/// API calls to access resources in the account that owns the role. You cannot use session
/// policies to grant more permissions than those allowed by the identity-based policy
/// of the role that is being assumed. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session">Session
/// Policies</a> in the <i>IAM User Guide</i>.
/// </para>
/// </summary>
public List<PolicyDescriptorType> PolicyArns
{
get { return this._policyArns; }
set { this._policyArns = value; }
}
// Check to see if PolicyArns property is set
internal bool IsSetPolicyArns()
{
return this._policyArns != null && this._policyArns.Count > 0;
}
/// <summary>
/// Gets and sets the property PrincipalArn.
/// <para>
/// The Amazon Resource Name (ARN) of the SAML provider in IAM that describes the IdP.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=20, Max=2048)]
public string PrincipalArn
{
get { return this._principalArn; }
set { this._principalArn = value; }
}
// Check to see if PrincipalArn property is set
internal bool IsSetPrincipalArn()
{
return this._principalArn != null;
}
/// <summary>
/// Gets and sets the property RoleArn.
/// <para>
/// The Amazon Resource Name (ARN) of the role that the caller is assuming.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=20, Max=2048)]
public string RoleArn
{
get { return this._roleArn; }
set { this._roleArn = value; }
}
// Check to see if RoleArn property is set
internal bool IsSetRoleArn()
{
return this._roleArn != null;
}
/// <summary>
/// Gets and sets the property SAMLAssertion.
/// <para>
/// The base-64 encoded SAML authentication response provided by the IdP.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html">Configuring
/// a Relying Party and Adding Claims</a> in the <i>IAM User Guide</i>.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=4, Max=100000)]
public string SAMLAssertion
{
get { return this._samlAssertion; }
set { this._samlAssertion = value; }
}
// Check to see if SAMLAssertion property is set
internal bool IsSetSAMLAssertion()
{
return this._samlAssertion != null;
}
}
} | 50.208122 | 203 | 0.645081 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/SecurityToken/Generated/Model/AssumeRoleWithSAMLRequest.cs | 19,786 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Threax.Home.Core
{
public enum Units
{
None,
Fahrenheit,
Celsius,
Lux,
Percent
}
}
| 13.375 | 33 | 0.579439 | [
"MIT"
] | threax/Threax.Home | Threax.Home.Core/Units.cs | 216 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace GraphProject
{
/// <summary>
/// This class handles the result from the multiple backtest Gui.
/// The chosen backtest period from the Gui, is translated to a
/// start and end indexes for backtest to be tested.
/// </summary>
public class BacktestPeriodPicker
{
private List<DailyDataPoint> _dataList;
public BacktestPeriodPicker(List<DailyDataPoint> dataList)
{
_dataList = dataList;
}
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public void PickIndexesForPeriod(int cbxIndex)
{
switch (cbxIndex)
{
case 0:
PeriodAllData();
break;
case 1:
PeriodTestSample(0.70);
break;
case 2:
PeriodOutOfSample(0.30);
break;
}
}
private void PeriodAllData()
{
StartIndex = 0;
EndIndex = _dataList.Count - 1;
}
private void PeriodTestSample(double periodFraction)
{
int nbr;
StartIndex = 0;
EndIndex = _dataList.Count - 1;
if (periodFraction > 0.0 && periodFraction < 1.0)
{
// Casted downward ex. 0.9 to 0
nbr = (int)(_dataList.Count * periodFraction);
EndIndex = nbr;
double treshold = 1.0 / _dataList.Count;
if (nbr < treshold)
MessageBox.Show(string.Format("Cant pick that small fraction with this little data! Pick {0} or bigger!", treshold));
}
else
MessageBox.Show("Fraction needs to be > 0.0 and < 1.0!");
}
private void PeriodOutOfSample(double periodFraction)
{
int nbr;
StartIndex = 0;
EndIndex = _dataList.Count - 1;
if (periodFraction > 0.0 && periodFraction < 1.0)
{
// Casted downward ex. 0.9 to 0
nbr = (int)(_dataList.Count * periodFraction);
double treshold = 1.0 / _dataList.Count;
if (nbr > 0)
StartIndex = _dataList.Count - nbr;
else
MessageBox.Show(string.Format("Cant pick that small fraction with this little data! Pick bigger than {0}!", treshold));
}
else
MessageBox.Show("Fraction needs to be > 0.0 and < 1.0!");
}
public DateTime GetStartDate()
{
return _dataList[StartIndex].Date;
}
public DateTime GetEndDate()
{
return _dataList[EndIndex].Date;
}
}
}
| 29.353535 | 139 | 0.502065 | [
"MIT"
] | Fibfractal/StockBacktester | GraphProject/GUIs/For Gui/Gui multiple backtest/BacktestPeriodPicker.cs | 2,908 | C# |
using System;
using CodeFuller.Library.Logging.Interfaces;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
namespace CodeFuller.Library.Logging.Internal
{
internal class RollingLogSink : ILogEventSink
{
private readonly ITextFormatter formatter;
private readonly IRollingLogFile rollingLogFile;
public RollingLogSink(ITextFormatter formatter, IRollingLogFile rollingLogFile)
{
this.formatter = formatter ?? throw new ArgumentNullException(nameof(formatter));
this.rollingLogFile = rollingLogFile ?? throw new ArgumentNullException(nameof(rollingLogFile));
}
public void Emit(LogEvent logEvent)
{
_ = logEvent ?? throw new ArgumentNullException(nameof(logEvent));
lock (formatter)
{
formatter.Format(logEvent, rollingLogFile.StreamWriter);
}
}
}
}
| 26.40625 | 100 | 0.747929 | [
"MIT"
] | CodeFuller/library | src/CodeFuller.Library.Logging/Internal/RollingLogSink.cs | 847 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MasGlobal.Core;
using MasGlobal.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace MasG.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
// GET api/values
[HttpGet]
public List<Employee> Get()
{
IEmployeeService services = new EmployeeService();
return services.GetEmployees();
}
// GET api/values/5
[HttpGet("{id}")]
public Employee Get(int id)
{
IEmployeeService services = new EmployeeService();
return services.GetEmployeeById(id);
}
}
} | 23.676471 | 62 | 0.619876 | [
"MIT"
] | lauramartinezing/employeesapp | MasG.API/Controllers/EmployeesController.cs | 807 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EuphoricElephant.Helpers
{
public static class ApplicationSettings
{
private static Dictionary<string, object> _settingsCache = new Dictionary<string, object>();
public static void AddItem(string itemKey, object itemValue)
{
_settingsCache.Add(itemKey, itemValue);
}
public static object GetItem(string itemKey)
{
return _settingsCache[itemKey];
}
public static bool Contains(string itemKey)
{
return _settingsCache.ContainsKey(itemKey);
}
public static void Remove(string itemKey)
{
if (ApplicationSettings.Contains(itemKey))
{
_settingsCache.Remove(itemKey);
}
}
public static void Edit(string itemKey, object itemValue)
{
Remove(itemKey);
AddItem(itemKey, itemValue);
}
}
}
| 24.883721 | 100 | 0.600935 | [
"MIT"
] | pxlit-projects/entmob2016_9 | EuphoricElephant/EuphoricElephant/Helpers/ApplicationSettings.cs | 1,072 | C# |
namespace MarketingBox.Sdk.Common.Tests.AttributesTests;
public class AdvancedCompareAttributeTests
{
} | 18.166667 | 56 | 0.825688 | [
"MIT"
] | MyJetMarketingBox/MarketingBox.Sdk.Common | test/MarketingBox.Sdk.Common.Tests/AttributesTests/AdvancedCompareAttributeTests.cs | 109 | C# |
using System;
using System.Collections.Generic;
using Unity.Collections;
namespace UnityEngine.Rendering.Distilling.Internal
{
/// <summary>
/// Renders a shadow map atlas for additional shadow-casting Lights.
/// </summary>
public class AdditionalLightsShadowCasterPass : ScriptableRenderPass
{
private static class AdditionalShadowsConstantBuffer
{
public static int _AdditionalLightsWorldToShadow;
public static int _AdditionalShadowParams;
public static int _AdditionalShadowOffset0;
public static int _AdditionalShadowOffset1;
public static int _AdditionalShadowOffset2;
public static int _AdditionalShadowOffset3;
public static int _AdditionalShadowmapSize;
}
public static int m_AdditionalShadowsBufferId;
public static int m_AdditionalShadowsIndicesId;
bool m_UseStructuredBuffer;
const int k_ShadowmapBufferBits = 16;
private RenderTargetHandle m_AdditionalLightsShadowmap;
RenderTexture m_AdditionalLightsShadowmapTexture;
int m_ShadowmapWidth;
int m_ShadowmapHeight;
ShadowSliceData[] m_AdditionalLightSlices = null;
// Shader data for UBO path
Matrix4x4[] m_AdditionalLightsWorldToShadow = null;
Vector4[] m_AdditionalLightsShadowParams = null;
int[] m_VisibleLightIndexToAdditionalLightIndex = null;
// Shader data for SSBO
ShaderInput.ShadowData[] m_AdditionalLightsShadowData = null;
List<int> m_AdditionalShadowCastingLightIndices = new List<int>();
List<int> m_AdditionalShadowCastingLightIndicesMap = new List<int>();
bool m_SupportsBoxFilterForShadows;
const string m_ProfilerTag = "Render Additional Shadows";
ProfilingSampler m_ProfilingSampler = new ProfilingSampler(m_ProfilerTag);
public AdditionalLightsShadowCasterPass(RenderPassEvent evt)
{
renderPassEvent = evt;
AdditionalShadowsConstantBuffer._AdditionalLightsWorldToShadow = Shader.PropertyToID("_AdditionalLightsWorldToShadow");
AdditionalShadowsConstantBuffer._AdditionalShadowParams = Shader.PropertyToID("_AdditionalShadowParams");
AdditionalShadowsConstantBuffer._AdditionalShadowOffset0 = Shader.PropertyToID("_AdditionalShadowOffset0");
AdditionalShadowsConstantBuffer._AdditionalShadowOffset1 = Shader.PropertyToID("_AdditionalShadowOffset1");
AdditionalShadowsConstantBuffer._AdditionalShadowOffset2 = Shader.PropertyToID("_AdditionalShadowOffset2");
AdditionalShadowsConstantBuffer._AdditionalShadowOffset3 = Shader.PropertyToID("_AdditionalShadowOffset3");
AdditionalShadowsConstantBuffer._AdditionalShadowmapSize = Shader.PropertyToID("_AdditionalShadowmapSize");
m_AdditionalLightsShadowmap.Init("_AdditionalLightsShadowmapTexture");
m_AdditionalShadowsBufferId = Shader.PropertyToID("_AdditionalShadowsBuffer");
m_AdditionalShadowsIndicesId = Shader.PropertyToID("_AdditionalShadowsIndices");
m_UseStructuredBuffer = RenderingUtils.useStructuredBuffer;
m_SupportsBoxFilterForShadows = Application.isMobilePlatform || SystemInfo.graphicsDeviceType == GraphicsDeviceType.Switch;
if (!m_UseStructuredBuffer)
{
// Preallocated a fixed size. CommandBuffer.SetGlobal* does allow this data to grow.
int maxLights = DistillingRenderPipeline.maxVisibleAdditionalLights;
m_AdditionalLightsWorldToShadow = new Matrix4x4[maxLights];
m_AdditionalLightsShadowParams = new Vector4[maxLights];
m_VisibleLightIndexToAdditionalLightIndex = new int[maxLights];
}
}
public bool Setup(ref RenderingData renderingData)
{
Clear();
m_ShadowmapWidth = renderingData.shadowData.additionalLightsShadowmapWidth;
m_ShadowmapHeight = renderingData.shadowData.additionalLightsShadowmapHeight;
var visibleLights = renderingData.lightData.visibleLights;
int additionalLightsCount = renderingData.lightData.additionalLightsCount;
if (m_AdditionalLightSlices == null || m_AdditionalLightSlices.Length < additionalLightsCount)
m_AdditionalLightSlices = new ShadowSliceData[additionalLightsCount];
if (m_AdditionalLightsShadowData == null || m_AdditionalLightsShadowData.Length < additionalLightsCount)
m_AdditionalLightsShadowData = new ShaderInput.ShadowData[additionalLightsCount];
if (m_VisibleLightIndexToAdditionalLightIndex.Length < visibleLights.Length)
{
m_VisibleLightIndexToAdditionalLightIndex = new int[visibleLights.Length];
}
int validShadowCastingLights = 0;
bool supportsSoftShadows = renderingData.shadowData.supportsSoftShadows;
for (int i = 0; i < visibleLights.Length && m_AdditionalShadowCastingLightIndices.Count < additionalLightsCount; ++i)
{
VisibleLight shadowLight = visibleLights[i];
m_VisibleLightIndexToAdditionalLightIndex[i] = i;
// Skip main directional light as it is not packed into the shadow atlas
if (i == renderingData.lightData.mainLightIndex)
continue;
int shadowCastingLightIndex = m_AdditionalShadowCastingLightIndices.Count;
bool isValidShadowSlice = false;
if (renderingData.cullResults.GetShadowCasterBounds(i, out var bounds))
{
// We need to iterate the lights even though additional lights are disabled because
// cullResults.GetShadowCasterBounds() does the fence sync for the shadow culling jobs.
if (!renderingData.shadowData.supportsAdditionalLightShadows)
{
continue;
}
if (IsValidShadowCastingLight(ref renderingData.lightData, i))
{
bool success = ShadowUtils.ExtractSpotLightMatrix(ref renderingData.cullResults,
ref renderingData.shadowData,
i,
out var shadowTransform,
out m_AdditionalLightSlices[shadowCastingLightIndex].viewMatrix,
out m_AdditionalLightSlices[shadowCastingLightIndex].projectionMatrix);
if (success)
{
m_AdditionalShadowCastingLightIndices.Add(i);
var light = shadowLight.light;
float shadowStrength = light.shadowStrength;
float softShadows = (supportsSoftShadows && light.shadows == LightShadows.Soft) ? 1.0f : 0.0f;
Vector4 shadowParams = new Vector4(shadowStrength, softShadows, 0.0f, 0.0f);
if (m_UseStructuredBuffer)
{
m_AdditionalLightsShadowData[shadowCastingLightIndex].worldToShadowMatrix = shadowTransform;
m_AdditionalLightsShadowData[shadowCastingLightIndex].shadowParams = shadowParams;
}
else
{
m_AdditionalLightsWorldToShadow[shadowCastingLightIndex] = shadowTransform;
m_AdditionalLightsShadowParams[shadowCastingLightIndex] = shadowParams;
}
isValidShadowSlice = true;
validShadowCastingLights++;
}
}
}
if (m_UseStructuredBuffer)
{
// When using StructuredBuffers all the valid shadow casting slices data
// are stored in a the ShadowData buffer and then we setup a index map to
// map from light indices to shadow buffer index. A index map of -1 means
// the light is not a valid shadow casting light and there's no data for it
// in the shadow buffer.
int indexMap = (isValidShadowSlice) ? shadowCastingLightIndex : -1;
m_AdditionalShadowCastingLightIndicesMap.Add(indexMap);
}
else if (!isValidShadowSlice)
{
// When NOT using structured buffers we have no performant way to sample the
// index map as int[]. Unity shader compiler converts int[] to float4[] to force memory alignment.
// This makes indexing int[] arrays very slow. So, in order to avoid indexing shadow lights we
// setup slice data and reserve shadow map space even for invalid shadow slices.
// The data is setup with zero shadow strength. This has the same visual effect of no shadow
// attenuation contribution from this light.
// This makes sampling shadow faster but introduces waste in shadow map atlas.
// The waste increases with the amount of additional lights to shade.
// Therefore Universal RP try to keep the limit at sane levels when using uniform buffers.
Matrix4x4 identity = Matrix4x4.identity;
m_AdditionalShadowCastingLightIndices.Add(i);
m_AdditionalLightsWorldToShadow[shadowCastingLightIndex] = identity;
m_AdditionalLightsShadowParams[shadowCastingLightIndex] = Vector4.zero;
m_AdditionalLightSlices[shadowCastingLightIndex].viewMatrix = identity;
m_AdditionalLightSlices[shadowCastingLightIndex].projectionMatrix = identity;
}
}
// Lights that need to be rendered in the shadow map atlas
if (validShadowCastingLights == 0)
return false;
int atlasWidth = renderingData.shadowData.additionalLightsShadowmapWidth;
int atlasHeight = renderingData.shadowData.additionalLightsShadowmapHeight;
int sliceResolution = ShadowUtils.GetMaxTileResolutionInAtlas(atlasWidth, atlasHeight, validShadowCastingLights);
// In the UI we only allow for square shadow map atlas. Here we check if we can fit
// all shadow slices into half resolution of the atlas and adjust height to have tighter packing.
int maximumSlices = (m_ShadowmapWidth / sliceResolution) * (m_ShadowmapHeight / sliceResolution);
if (validShadowCastingLights <= (maximumSlices / 2))
m_ShadowmapHeight /= 2;
int shadowSlicesPerRow = (atlasWidth / sliceResolution);
float oneOverAtlasWidth = 1.0f / m_ShadowmapWidth;
float oneOverAtlasHeight = 1.0f / m_ShadowmapHeight;
int sliceIndex = 0;
int shadowCastingLightsBufferCount = m_AdditionalShadowCastingLightIndices.Count;
Matrix4x4 sliceTransform = Matrix4x4.identity;
sliceTransform.m00 = sliceResolution * oneOverAtlasWidth;
sliceTransform.m11 = sliceResolution * oneOverAtlasHeight;
for (int i = 0; i < shadowCastingLightsBufferCount; ++i)
{
// we can skip the slice if strength is zero. Some slices with zero
// strength exists when using uniform array path.
if (!m_UseStructuredBuffer && Mathf.Approximately(m_AdditionalLightsShadowParams[i].x, 0.0f))
continue;
m_AdditionalLightSlices[i].offsetX = (sliceIndex % shadowSlicesPerRow) * sliceResolution;
m_AdditionalLightSlices[i].offsetY = (sliceIndex / shadowSlicesPerRow) * sliceResolution;
m_AdditionalLightSlices[i].resolution = sliceResolution;
sliceTransform.m03 = m_AdditionalLightSlices[i].offsetX * oneOverAtlasWidth;
sliceTransform.m13 = m_AdditionalLightSlices[i].offsetY * oneOverAtlasHeight;
// We bake scale and bias to each shadow map in the atlas in the matrix.
// saves some instructions in shader.
if (m_UseStructuredBuffer)
m_AdditionalLightsShadowData[i].worldToShadowMatrix = sliceTransform * m_AdditionalLightsShadowData[i].worldToShadowMatrix;
else
m_AdditionalLightsWorldToShadow[i] = sliceTransform * m_AdditionalLightsWorldToShadow[i];
sliceIndex++;
}
return true;
}
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
m_AdditionalLightsShadowmapTexture = ShadowUtils.GetTemporaryShadowTexture(m_ShadowmapWidth, m_ShadowmapHeight, k_ShadowmapBufferBits);
ConfigureTarget(new RenderTargetIdentifier(m_AdditionalLightsShadowmapTexture));
ConfigureClear(ClearFlag.All, Color.black);
}
/// <inheritdoc/>
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
if (renderingData.shadowData.supportsAdditionalLightShadows)
RenderAdditionalShadowmapAtlas(ref context, ref renderingData.cullResults, ref renderingData.lightData, ref renderingData.shadowData);
}
public override void FrameCleanup(CommandBuffer cmd)
{
if (cmd == null)
throw new ArgumentNullException("cmd");
if (m_AdditionalLightsShadowmapTexture)
{
RenderTexture.ReleaseTemporary(m_AdditionalLightsShadowmapTexture);
m_AdditionalLightsShadowmapTexture = null;
}
}
public int GetShadowLightIndexFromLightIndex(int visibleLightIndex)
{
if (visibleLightIndex < 0 || visibleLightIndex >= m_VisibleLightIndexToAdditionalLightIndex.Length)
return -1;
return m_VisibleLightIndexToAdditionalLightIndex[visibleLightIndex];
}
void Clear()
{
m_AdditionalShadowCastingLightIndices.Clear();
m_AdditionalShadowCastingLightIndicesMap.Clear();
m_AdditionalLightsShadowmapTexture = null;
}
void RenderAdditionalShadowmapAtlas(ref ScriptableRenderContext context, ref CullingResults cullResults, ref LightData lightData, ref ShadowData shadowData)
{
NativeArray<VisibleLight> visibleLights = lightData.visibleLights;
bool additionalLightHasSoftShadows = false;
CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag);
using (new ProfilingScope(cmd, m_ProfilingSampler))
{
bool anyShadowSliceRenderer = false;
int shadowSlicesCount = m_AdditionalShadowCastingLightIndices.Count;
for (int i = 0; i < shadowSlicesCount; ++i)
{
// we do the shadow strength check here again here because when using
// the uniform array path we might have zero strength shadow lights.
// In that case we need the shadow data buffer but we can skip
// rendering them to shadowmap.
if (!m_UseStructuredBuffer && Mathf.Approximately(m_AdditionalLightsShadowParams[i].x, 0.0f))
continue;
// Index of the VisibleLight
int shadowLightIndex = m_AdditionalShadowCastingLightIndices[i];
VisibleLight shadowLight = visibleLights[shadowLightIndex];
ShadowSliceData shadowSliceData = m_AdditionalLightSlices[i];
var settings = new ShadowDrawingSettings(cullResults, shadowLightIndex);
Vector4 shadowBias = ShadowUtils.GetShadowBias(ref shadowLight, shadowLightIndex,
ref shadowData, shadowSliceData.projectionMatrix, shadowSliceData.resolution);
ShadowUtils.SetupShadowCasterConstantBuffer(cmd, ref shadowLight, shadowBias);
ShadowUtils.RenderShadowSlice(cmd, ref context, ref shadowSliceData, ref settings);
additionalLightHasSoftShadows |= shadowLight.light.shadows == LightShadows.Soft;
anyShadowSliceRenderer = true;
}
// We share soft shadow settings for main light and additional lights to save keywords.
// So we check here if pipeline supports soft shadows and either main light or any additional light has soft shadows
// to enable the keyword.
// TODO: In PC and Consoles we can upload shadow data per light and branch on shader. That will be more likely way faster.
bool mainLightHasSoftShadows = shadowData.supportsMainLightShadows &&
lightData.mainLightIndex != -1 &&
visibleLights[lightData.mainLightIndex].light.shadows ==
LightShadows.Soft;
bool softShadows = shadowData.supportsSoftShadows &&
(mainLightHasSoftShadows || additionalLightHasSoftShadows);
CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.AdditionalLightShadows, anyShadowSliceRenderer);
CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.SoftShadows, softShadows);
if (anyShadowSliceRenderer)
SetupAdditionalLightsShadowReceiverConstants(cmd, ref shadowData, softShadows);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
void SetupAdditionalLightsShadowReceiverConstants(CommandBuffer cmd, ref ShadowData shadowData, bool softShadows)
{
int shadowLightsCount = m_AdditionalShadowCastingLightIndices.Count;
float invShadowAtlasWidth = 1.0f / shadowData.additionalLightsShadowmapWidth;
float invShadowAtlasHeight = 1.0f / shadowData.additionalLightsShadowmapHeight;
float invHalfShadowAtlasWidth = 0.5f * invShadowAtlasWidth;
float invHalfShadowAtlasHeight = 0.5f * invShadowAtlasHeight;
cmd.SetGlobalTexture(m_AdditionalLightsShadowmap.id, m_AdditionalLightsShadowmapTexture);
if (m_UseStructuredBuffer)
{
NativeArray<ShaderInput.ShadowData> shadowBufferData = new NativeArray<ShaderInput.ShadowData>(shadowLightsCount, Allocator.Temp);
for (int i = 0; i < shadowLightsCount; ++i)
{
ShaderInput.ShadowData data;
data.worldToShadowMatrix = m_AdditionalLightsShadowData[i].worldToShadowMatrix;
data.shadowParams = m_AdditionalLightsShadowData[i].shadowParams;
shadowBufferData[i] = data;
}
var shadowBuffer = ShaderData.instance.GetShadowDataBuffer(shadowLightsCount);
shadowBuffer.SetData(shadowBufferData);
var shadowIndicesMapBuffer = ShaderData.instance.GetShadowIndicesBuffer(m_AdditionalShadowCastingLightIndicesMap.Count);
shadowIndicesMapBuffer.SetData(m_AdditionalShadowCastingLightIndicesMap, 0, 0,
m_AdditionalShadowCastingLightIndicesMap.Count);
cmd.SetGlobalBuffer(m_AdditionalShadowsBufferId, shadowBuffer);
cmd.SetGlobalBuffer(m_AdditionalShadowsIndicesId, shadowIndicesMapBuffer);
shadowBufferData.Dispose();
}
else
{
cmd.SetGlobalMatrixArray(AdditionalShadowsConstantBuffer._AdditionalLightsWorldToShadow, m_AdditionalLightsWorldToShadow);
cmd.SetGlobalVectorArray(AdditionalShadowsConstantBuffer._AdditionalShadowParams, m_AdditionalLightsShadowParams);
}
if (softShadows)
{
if (m_SupportsBoxFilterForShadows)
{
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowOffset0,
new Vector4(-invHalfShadowAtlasWidth, -invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowOffset1,
new Vector4(invHalfShadowAtlasWidth, -invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowOffset2,
new Vector4(-invHalfShadowAtlasWidth, invHalfShadowAtlasHeight, 0.0f, 0.0f));
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowOffset3,
new Vector4(invHalfShadowAtlasWidth, invHalfShadowAtlasHeight, 0.0f, 0.0f));
}
// Currently only used when !SHADER_API_MOBILE but risky to not set them as it's generic
// enough so custom shaders might use it.
cmd.SetGlobalVector(AdditionalShadowsConstantBuffer._AdditionalShadowmapSize, new Vector4(invShadowAtlasWidth, invShadowAtlasHeight,
shadowData.additionalLightsShadowmapWidth, shadowData.additionalLightsShadowmapHeight));
}
}
bool IsValidShadowCastingLight(ref LightData lightData, int i)
{
if (i == lightData.mainLightIndex)
return false;
VisibleLight shadowLight = lightData.visibleLights[i];
// Directional and Point light shadows are not supported in the shadow map atlas
if (shadowLight.lightType == LightType.Point || shadowLight.lightType == LightType.Directional)
return false;
Light light = shadowLight.light;
return light != null && light.shadows != LightShadows.None && !Mathf.Approximately(light.shadowStrength, 0.0f);
}
}
}
| 55.243842 | 164 | 0.643141 | [
"MIT"
] | Kirkice/DistillingRenderPipeline | Assets/Distilling RP/Runtime/Passes/AdditionalLightsShadowCasterPass.cs | 22,429 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Pomidor
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.956522 | 66 | 0.583333 | [
"MIT"
] | Pioziomgames/pomidor | Program.cs | 530 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.BAASDT.Models
{
public class QueryBlockanalysisDelegaterelationResponse : TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
[NameInMap("req_msg_id")]
[Validation(Required=false)]
public string ReqMsgId { get; set; }
// 结果码,一般OK表示调用成功
[NameInMap("result_code")]
[Validation(Required=false)]
public string ResultCode { get; set; }
// 异常信息的文本描述
[NameInMap("result_msg")]
[Validation(Required=false)]
public string ResultMsg { get; set; }
// 代理授权关系信息
[NameInMap("delegate_relation_infos")]
[Validation(Required=false)]
public List<DelegateRelationInfo> DelegateRelationInfos { get; set; }
}
}
| 24.857143 | 77 | 0.643678 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | baasdt/csharp/core/Models/QueryBlockanalysisDelegaterelationResponse.cs | 960 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.AutoML;
using Microsoft.Extensions.DependencyInjection;
using MLNETMLFlowSampleConsole.Domain;
using MLFlow.NET.Lib;
using MLFlow.NET.Lib.Contract;
using MLFlow.NET.Lib.Model;
using MLFlow.NET.Lib.Model.Responses.Experiment;
using MLFlow.NET.Lib.Model.Responses.Run;
namespace MLNETMLFlowSampleConsole
{
class Program
{
private readonly static IMLFlowService _mlFlowService;
static Program()
{
// Initialize app configuration
var appConfig = new Startup();
appConfig.ConfigureServices();
// Initialize MLFlow service
_mlFlowService = appConfig.Services.GetService<IMLFlowService>();
}
static async Task Main(string[] args)
{
// Run experiment
await RunExperiment();
}
public static async Task RunExperiment()
{
// 1. Create MLContext
MLContext ctx = new MLContext();
// 2. Load data
IDataView data = ctx.Data.LoadFromTextFile<IrisData>("Data/iris.data", separatorChar: ',');
// 3. Define Automated ML.NET experiment settings
var experimentSettings = new MulticlassExperimentSettings();
experimentSettings.MaxExperimentTimeInSeconds = 30;
experimentSettings.OptimizingMetric = MulticlassClassificationMetric.LogLoss;
// 4. Create Automated ML.NET
var experiment = ctx.Auto().CreateMulticlassClassificationExperiment(experimentSettings);
// 5. Create experiment in MLFlow
var experimentName = Guid.NewGuid().ToString();
var experimentRequest = await _mlFlowService.GetOrCreateExperiment(experimentName);
// 6. Run Automated ML.NET experiment
var experimentResults = experiment.Execute(data, progressHandler: new ProgressHandler());
// 7. Log Best Run
LogRun(experimentRequest.ExperimentId,experimentResults);
string savePath = Path.Join("MLModels", $"{experimentName}");
string modelPath = Path.Join(savePath, "model.zip");
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
// 8. Save Best Trained Model
ctx.Model.Save(experimentResults.BestRun.Model, data.Schema, modelPath);
}
static async void LogRun(int experimentId, ExperimentResult<MulticlassClassificationMetrics> experimentResults)
{
// Define run
var runObject = new CreateRunRequest();
runObject.ExperimentId = experimentId;
runObject.StartTime = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeMilliseconds();
runObject.UserId = Environment.UserName;
runObject.SourceType = SourceType.LOCAL;
// Create new run in MLFlow
var runRequest = await _mlFlowService.CreateRun(runObject);
// Get information for best run
var runDetails = experimentResults.BestRun;
// Log trainer name
await _mlFlowService.LogParameter(runRequest.Run.Info.RunUuid, nameof(runDetails.TrainerName), runDetails.TrainerName);
// Log metrics
await _mlFlowService.LogMetric(runRequest.Run.Info.RunUuid, nameof(runDetails.RuntimeInSeconds), (float)runDetails.RuntimeInSeconds);
await _mlFlowService.LogMetric(runRequest.Run.Info.RunUuid, nameof(runDetails.ValidationMetrics.LogLoss), (float)runDetails.ValidationMetrics.LogLoss);
await _mlFlowService.LogMetric(runRequest.Run.Info.RunUuid, nameof(runDetails.ValidationMetrics.MacroAccuracy), (float)runDetails.ValidationMetrics.MacroAccuracy);
await _mlFlowService.LogMetric(runRequest.Run.Info.RunUuid, nameof(runDetails.ValidationMetrics.MicroAccuracy), (float)runDetails.ValidationMetrics.MicroAccuracy);
}
}
}
| 41.98 | 176 | 0.648404 | [
"MIT"
] | lqdev/MLNETMLFlowSample | MLNETMLFlowSampleConsole/Program.cs | 4,200 | C# |
// IBehaviourPool.cs created with MonoDevelop
// User: stefant at 17:19 07/28/2008
//
using System;
using System.Collections.Generic;
namespace Alica
{
/// <summary>
/// An engine trigger is a delegate used to call eventDriven <see cref="BasicBehaviour"/>s. Events of this type can be used by a BasicBehaviour to manage when it is called.
/// </summary>
public delegate void EngineTrigger(object arg);
/// <summary>
/// An IBehaviourPool manages the actual behaviours controlling the agent's actuators.
/// </summary>
public interface IBehaviourPool
{
/// <summary>
/// Indicates whether a class for a specific behaviour was succesfully loaded and is available.
/// </summary>
/// <param name="b">
/// A <see cref="Behaviour"/>
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
bool IsBehaviourAvailable(Behaviour b);
/// <summary>
/// Add a behaviour represented by its RunningPlan to the set of currently active behaviour. Usually called by the <see cref="RunningPlan"/>.
/// </summary>
/// <param name="rp">
/// A <see cref="RunningPlan"/>
/// </param>
void AddBehaviour(RunningPlan rp);
/// <summary>
/// Remove a behaviour represented by its RunningPlan from the set of currently active behaviour. Usually called by the <see cref="RunningPlan"/>.
/// </summary>
/// <param name="rp">
/// A <see cref="RunningPlan"/>
/// </param>
void RemoveBehaviour(RunningPlan rp);
/// <summary>
/// Initialises this Engine Module
/// </summary>
void Init();
/// <summary>
/// Stops this engine module
/// </summary>
void Stop();
}
}
| 27.830508 | 173 | 0.661389 | [
"BSD-3-Clause-Clear"
] | RedundantEntry/cn-alica-ros-pkg | AlicaEngine/src/Engine/IBehaviourPool.cs | 1,643 | 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 lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Lightsail.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Lightsail.Model.Internal.MarshallTransformations
{
/// <summary>
/// AttachInstancesToLoadBalancer Request Marshaller
/// </summary>
public class AttachInstancesToLoadBalancerRequestMarshaller : IMarshaller<IRequest, AttachInstancesToLoadBalancerRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((AttachInstancesToLoadBalancerRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(AttachInstancesToLoadBalancerRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Lightsail");
string target = "Lightsail_20161128.AttachInstancesToLoadBalancer";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetInstanceNames())
{
context.Writer.WritePropertyName("instanceNames");
context.Writer.WriteArrayStart();
foreach(var publicRequestInstanceNamesListValue in publicRequest.InstanceNames)
{
context.Writer.Write(publicRequestInstanceNamesListValue);
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetLoadBalancerName())
{
context.Writer.WritePropertyName("loadBalancerName");
context.Writer.Write(publicRequest.LoadBalancerName);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static AttachInstancesToLoadBalancerRequestMarshaller _instance = new AttachInstancesToLoadBalancerRequestMarshaller();
internal static AttachInstancesToLoadBalancerRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static AttachInstancesToLoadBalancerRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.491379 | 173 | 0.63003 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/AttachInstancesToLoadBalancerRequestMarshaller.cs | 4,349 | C# |
using System.Collections.Generic;
namespace RegExpService
{
/// <summary>Kimenet szerintt csoportosítást leíró osztály.</summary>
internal class MatchGroupedInfoList
{
/// <summary>Érték/index pár beállítása.</summary>
/// <param name="pValue">Talált karakterlánc érték.</param>
/// <param name="pIndex">Kezdőpozíció az eredeti karakterláncban.</param>
internal void Set(string pValue, int pIndex)
{
MatchGroupedInfo matchGroupedInfo = matchGroupedInfoList.Find(x => x.Value == pValue);
if (matchGroupedInfo == null)
{
matchGroupedInfoList.Add(new(pValue, pIndex));
return;
}
matchGroupedInfo.Add(pIndex);
}
/// <summary>Az összes azonos kimenetű találat információinak lekérdezése.</summary>
/// <returns>Azonos kimenetű találatok információit tartalmazó lista.</returns>
internal MatchGroupedInfo[] GetMatchGroupedInfos()
{
return matchGroupedInfoList.ToArray();
}
#region Privát terület!
readonly List<MatchGroupedInfo> matchGroupedInfoList = new();
#endregion
}
} | 33.5 | 98 | 0.629353 | [
"MIT"
] | tas-h/MiniRegExp | Library/RegExpService/MatchGroupedInfoList.cs | 1,241 | C# |
using System.Windows;
using System.Windows.Media;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using Modele;
namespace Appli
{
/// <summary>
/// Logique d'interaction pour PasswordChange.xaml
/// </summary>
public partial class PasswordChange : MetroWindow
{
private static Manager Man => (Application.Current as App)?.Man;
public PasswordChange()
{
InitializeComponent();
DataContext = Man.ConnectedUser;
}
private void OldPassword_OnPasswordChanged(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(OldPassword.Password))
{
OldPasswordHeader.Foreground = new SolidColorBrush { Color = Colors.Gray, Opacity = 0.3};
OldPasswordClear.IsEnabled = false;
}
else
{
OldPasswordHeader.Foreground = new SolidColorBrush { Color = Colors.Gray, Opacity = 0.0};
OldPasswordClear.IsEnabled = true;
}
}
private void OldPasswordClear_OnClick(object sender, RoutedEventArgs e) => OldPassword.Password = "";
private void NewPasswordCheck_OnPasswordChanged(object sender, RoutedEventArgs e)
{
if (NewPassword.Password.Equals(""))
{
NewPasswordHeader.Foreground = new SolidColorBrush { Color = Colors.Gray, Opacity = 0.3};
NewPasswordClear.IsEnabled = false;
}
else
{
NewPasswordHeader.Foreground = new SolidColorBrush { Color = Colors.Gray, Opacity = 0.0};
NewPasswordClear.IsEnabled = true;
}
}
private void NewPasswordCheckClear_OnClick(object sender, RoutedEventArgs e) => NewPassword.Password = "";
private void ChangePassword_OnClick(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(OldPassword.Password) || string.IsNullOrWhiteSpace(NewPassword.Password))
{
this.ShowModalMessageExternal("Erreur de changement de mot de passe", "Veuillez renseigner l'ancien puis le nouveau mot de passe.");
return;
}
var test = Manager.ChangerPassword(Man.ConnectedUser, OldPassword.Password, NewPassword.Password);
if (test)
{
Close();
return;
}
this.ShowModalMessageExternal("Erreur de changement de mot de passe", "Votre ancien mot de passe ne correspond pas, veuillez ressaisir");
}
}
}
| 36.555556 | 149 | 0.602964 | [
"MIT"
] | iShoFen/Cinema | Source/Cinema/Appli/PasswordChange.xaml.cs | 2,634 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using DevelopmentInProgress.WPFControls.Messaging;
using DevelopmentInProgress.WPFControls.Test.Models;
namespace DevelopmentInProgress.WPFControls.Test
{
public class MainViewModel : NotifyChange
{
public MainViewModel()
{
LoadMessages();
LoadUsers();
ShowMessageBoxes();
}
public ObservableCollection<Message> Messages { get; set; }
public ObservableCollection<User> Users { get; set; }
private void LoadMessages()
{
var messageError = new Message()
{
MessageType = MessageType.Error,
Text = "The role name is mandatory when creating or saving a role."
};
var messageWarn = new Message()
{
MessageType = MessageType.Warn,
Text = "Cannot create a new role with the name 'Writer' as one already exists."
};
var messageInfo = new Message()
{
MessageType = MessageType.Info,
Text = "User 'Joe Bloggs' has been granted the role 'Writer'."
};
Messages = new ObservableCollection<Message>(new List<Message> { messageError, messageWarn, messageInfo });
}
public void LoadUsers()
{
var read = new Activity {Text = "Read", Image = @"..\Images\Activities.png"};
var write = new Activity { Text = "Write", Image = @"..\Images\Activity_Write.png" };
var accept = new Activity { Text = "Accept", Image = @"..\Images\Activity_Accept.png" };
var reject = new Activity { Text = "Reject", Image = @"..\Images\Activity_Reject.png" };
var email = new Activity { Text = "Email", Image = @"..\Images\Activity_email.png" };
var writer = new Role {Text = "Writer", Image = @"..\Images\Role_Writer.png"};
var reviewer = new Role { Text = "Reviewer", Image = @"..\Images\Role_Reviewer.png" };
var administrator = new Role { Text = "Administrator", Image = @"..\Images\Role_Administrator.png" };
var joe = new User {Text = "Joe Bloggs", Image = @"..\Images\user.png"};
var jane = new User {Text = "Jane Masters", Image = @"..\Images\user.png"};
var john = new User {Text = "Jack Smith", Image = @"..\Images\user.png"};
writer.Activities.Add(read);
writer.Activities.Add(write);
reviewer.Activities.Add(read);
reviewer.Activities.Add(accept);
reviewer.Activities.Add(reject);
administrator.Activities.Add(read);
administrator.Activities.Add(write);
administrator.Activities.Add(accept);
administrator.Activities.Add(reject);
administrator.Activities.Add(email);
joe.Roles.Add(writer);
jane.Roles.Add(reviewer);
john.Roles.Add(administrator);
Users = new ObservableCollection<User>(new[] {joe, jane, john});
}
private void ShowMessageBoxes()
{
var info = new MessageBoxSettings
{
Title = "Grant User Role",
Text = "User 'Joe Bloggs' has been granted the role 'Writer'. Do you wish to continue?",
MessageType = MessageType.Info,
MessageBoxButtons = MessageBoxButtons.OkCancel
};
var infoResult = Dialog.ShowMessage(info);
var warn = new MessageBoxSettings
{
Title = "Create Role",
Text = "A role with the name 'Writer' already exists.\nDo you want to replace it?",
MessageType = MessageType.Warn,
MessageBoxButtons = MessageBoxButtons.YesNoCancel
};
var warnResult = Dialog.ShowMessage(warn);
var question = new MessageBoxSettings
{
Title = "Remove User From Role",
Text = "Do you want to remove user 'Jane Master' from the 'Reviewer' role?",
MessageType = MessageType.Question,
MessageBoxButtons = MessageBoxButtons.YesNo
};
var questionResult = Dialog.ShowMessage(question);
var error = new MessageBoxSettings
{
Title = "Create Role",
Text = "The role name is mandatory when creating or saving a role.",
MessageType = MessageType.Error,
MessageBoxButtons = MessageBoxButtons.Ok
};
Dialog.ShowMessage(error);
try
{
int zero = 0;
var result = 1/zero;
}
catch (Exception ex)
{
Dialog.ShowException(ex);
}
}
}
}
| 36.397059 | 119 | 0.549293 | [
"Apache-2.0"
] | grantcolley/wpfcontrols | DevelopmentInProgress.WPFControls.TestHarness/MainViewModel.cs | 4,952 | C# |
/// <summary>
/// If implement, Gameobject can be destroyed by player's ultimate.
/// </summary>
public interface IDestructible
{
/// <summary>
/// Called By Player Ultimate.
/// </summary>
void Destroy();
} | 18.833333 | 67 | 0.623894 | [
"MIT"
] | USBtheKey/Source_Danbar | Assets/Scripts/GameSystem/IDestructible.cs | 228 | C# |
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace MaterialSkin.Controls
{
///TODO: Break this out into a MaterialDialog then extend into the MaterialMsgBox
///Adapted from http://www.codeproject.com/Articles/601900/FlexibleMessageBox
public class MaterialMessageBox : IMaterialControl
{
[Browsable(false)]
public int Depth { get; set; }
[Browsable(false)]
public MaterialSkinManager SkinManager => MaterialSkinManager.Instance;
[Browsable(false)]
public MouseState MouseState { get; set; }
[Browsable(false)]
public Point MouseLocation { get; set; }
public static DialogResult Show(string text, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(null, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, UseRichTextBox);
}
public static DialogResult Show(IWin32Window owner, string text, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(owner, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, UseRichTextBox);
}
public static DialogResult Show(string text, string caption, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(null, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, UseRichTextBox);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(owner, text, caption, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, UseRichTextBox);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(null, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, UseRichTextBox);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(owner, text, caption, buttons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, UseRichTextBox);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(null, text, caption, buttons, icon, MessageBoxDefaultButton.Button1, UseRichTextBox);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(owner, text, caption, buttons, icon, MessageBoxDefaultButton.Button1, UseRichTextBox);
}
public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(null, text, caption, buttons, icon, defaultButton, UseRichTextBox);
}
public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, bool UseRichTextBox = true)
{
return FlexibleMaterialForm.Show(owner, text, caption, buttons, icon, defaultButton, UseRichTextBox);
}
}
}
| 49.146667 | 203 | 0.721378 | [
"MIT"
] | afrizaldm/MaterialSkin | MaterialSkin/Controls/MaterialMessageBox.cs | 3,688 | C# |
namespace PartlyRebuildIdentity.Data.Intefaces.IdentityStores
{
using Microsoft.AspNet.Identity;
using Models.Interfaces;
public interface IIdentitySecurityStampStore<TUser, in TKey> :
IIdentityStore<TUser, TKey>,
IUserSecurityStampStore<TUser, TKey>
where TUser : class, IIdentityApplicationUser<TKey>, IUser<TKey>
{
}
} | 30.583333 | 72 | 0.724796 | [
"MIT"
] | kraskoo/PartlyRebuildMicrosoftIdentityUser | PartlyRebuildIdentity.Data/Intefaces/IdentityStores/IIdentitySecurityStampStore.cs | 369 | C# |
namespace Sitecore.Feature.Accounts.Tests.Extensions
{
using NSubstitute;
using Ploeh.AutoFixture;
using Sitecore.FakeDb.Security.Accounts;
using Sitecore.Foundation.Testing.Attributes;
public class AutoFakeUserDataAttribute: AutoDbDataAttribute
{
public AutoFakeUserDataAttribute()
{
this.Fixture.Register(() =>
{
var user = Substitute.ForPartsOf<FakeMembershipUser>();
user.ProviderName.Returns("fake");
return user;
});
}
}
}
| 24.714286 | 64 | 0.666667 | [
"Apache-2.0"
] | 26384sunilrana/Habitat | src/Feature/Accounts/Tests/Extensions/AutoFakeUserDataAttribute.cs | 521 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ModelCloningPrivateSetArrayOfNullableChild1.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
// Sourced from OBeautifulCode.CodeGen.ModelObject.Test.CodeGeneratorTest
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.CodeGen.ModelObject.Test
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using FakeItEasy;
using OBeautifulCode.Assertion.Recipes;
using OBeautifulCode.CodeAnalysis.Recipes;
using OBeautifulCode.Equality.Recipes;
using OBeautifulCode.Type;
#pragma warning disable CS0659
#pragma warning disable CS0661
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = ObcSuppressBecause.CA1711_IdentifiersShouldNotHaveIncorrectSuffix_TypeNameAddedAsSuffixForTestsWhereTypeIsPrimaryConcern)]
public partial class ModelCloningPrivateSetArrayOfNullableChild1 : ModelCloningPrivateSetArrayOfNullableParent, IDeepCloneableViaCodeGen, IDeclareDeepCloneMethod<ModelCloningPrivateSetArrayOfNullableChild1>, IEquatable<ModelCloningPrivateSetArrayOfNullableChild1>
#pragma warning disable CS0659
#pragma warning disable CS0661
{
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
public ModelCloningPrivateSetArrayOfNullableChild1(
bool?[] parentArrayOfNullableBoolProperty,
int?[] parentArrayOfNullableIntProperty,
Guid?[] parentArrayOfNullableGuidProperty,
DateTime?[] parentArrayOfNullableDateTimeProperty,
CustomEnum?[] parentArrayOfNullableCustomEnumProperty,
CustomFlagsEnum?[] parentArrayOfNullableCustomFlagsEnumProperty,
bool?[] child1ArrayOfNullableBoolProperty,
int?[] child1ArrayOfNullableIntProperty,
Guid?[] child1ArrayOfNullableGuidProperty,
DateTime?[] child1ArrayOfNullableDateTimeProperty,
CustomEnum?[] child1ArrayOfNullableCustomEnumProperty,
CustomFlagsEnum?[] child1ArrayOfNullableCustomFlagsEnumProperty)
: base(parentArrayOfNullableBoolProperty, parentArrayOfNullableIntProperty, parentArrayOfNullableGuidProperty, parentArrayOfNullableDateTimeProperty, parentArrayOfNullableCustomEnumProperty, parentArrayOfNullableCustomFlagsEnumProperty)
{
new { child1ArrayOfNullableBoolProperty }.AsArg().Must().NotBeNullNorEmptyEnumerable();
new { child1ArrayOfNullableIntProperty }.AsArg().Must().NotBeNullNorEmptyEnumerable();
new { child1ArrayOfNullableGuidProperty }.AsArg().Must().NotBeNullNorEmptyEnumerable();
new { child1ArrayOfNullableDateTimeProperty }.AsArg().Must().NotBeNullNorEmptyEnumerable();
new { child1ArrayOfNullableCustomEnumProperty }.AsArg().Must().NotBeNullNorEmptyEnumerable();
new { child1ArrayOfNullableCustomFlagsEnumProperty }.AsArg().Must().NotBeNullNorEmptyEnumerable();
this.Child1ArrayOfNullableBoolProperty = child1ArrayOfNullableBoolProperty;
this.Child1ArrayOfNullableIntProperty = child1ArrayOfNullableIntProperty;
this.Child1ArrayOfNullableGuidProperty = child1ArrayOfNullableGuidProperty;
this.Child1ArrayOfNullableDateTimeProperty = child1ArrayOfNullableDateTimeProperty;
this.Child1ArrayOfNullableCustomEnumProperty = child1ArrayOfNullableCustomEnumProperty;
this.Child1ArrayOfNullableCustomFlagsEnumProperty = child1ArrayOfNullableCustomFlagsEnumProperty;
}
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public bool?[] Child1ArrayOfNullableBoolProperty { get; private set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public int?[] Child1ArrayOfNullableIntProperty { get; private set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public Guid?[] Child1ArrayOfNullableGuidProperty { get; private set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public DateTime?[] Child1ArrayOfNullableDateTimeProperty { get; private set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public CustomEnum?[] Child1ArrayOfNullableCustomEnumProperty { get; private set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public CustomFlagsEnum?[] Child1ArrayOfNullableCustomFlagsEnumProperty { get; private set; }
/// <inheritdoc />
public bool Equals(ModelCloningPrivateSetArrayOfNullableChild1 other)
{
if (ReferenceEquals(this, other))
{
return true;
}
if (ReferenceEquals(other, null))
{
return false;
}
var result =
this.ParentArrayOfNullableBoolProperty.IsEqualTo(other.ParentArrayOfNullableBoolProperty) &&
this.ParentArrayOfNullableIntProperty.IsEqualTo(other.ParentArrayOfNullableIntProperty) &&
this.ParentArrayOfNullableGuidProperty.IsEqualTo(other.ParentArrayOfNullableGuidProperty) &&
this.ParentArrayOfNullableDateTimeProperty.IsEqualTo(other.ParentArrayOfNullableDateTimeProperty) &&
this.ParentArrayOfNullableCustomEnumProperty.IsEqualTo(other.ParentArrayOfNullableCustomEnumProperty) &&
this.ParentArrayOfNullableCustomFlagsEnumProperty.IsEqualTo(other.ParentArrayOfNullableCustomFlagsEnumProperty) &&
this.Child1ArrayOfNullableBoolProperty.IsEqualTo(other.Child1ArrayOfNullableBoolProperty) &&
this.Child1ArrayOfNullableIntProperty.IsEqualTo(other.Child1ArrayOfNullableIntProperty) &&
this.Child1ArrayOfNullableGuidProperty.IsEqualTo(other.Child1ArrayOfNullableGuidProperty) &&
this.Child1ArrayOfNullableDateTimeProperty.IsEqualTo(other.Child1ArrayOfNullableDateTimeProperty) &&
this.Child1ArrayOfNullableCustomEnumProperty.IsEqualTo(other.Child1ArrayOfNullableCustomEnumProperty) &&
this.Child1ArrayOfNullableCustomFlagsEnumProperty.IsEqualTo(other.Child1ArrayOfNullableCustomFlagsEnumProperty);
return result;
}
/// <inheritdoc />
public override bool Equals(ModelCloningPrivateSetArrayOfNullableParent other)
{
var result = this.Equals((ModelCloningPrivateSetArrayOfNullableChild1)other);
return result;
}
/// <inheritdoc />
ModelCloningPrivateSetArrayOfNullableChild1 IDeclareDeepCloneMethod<ModelCloningPrivateSetArrayOfNullableChild1>.DeepClone()
{
var result = this.DeepCloneImplementation();
return result;
}
private ModelCloningPrivateSetArrayOfNullableChild1 DeepCloneImplementation()
{
var referenceModel = A.Dummy<ModelAllPrivateSetArrayOfNullableChild1>();
var referenceModelProperties = referenceModel.GetType().GetProperties();
foreach (var referenceModelProperty in referenceModelProperties)
{
referenceModelProperty.DeclaringType.GetProperty(referenceModelProperty.Name).SetValue(referenceModel, this.GetType().GetProperty(referenceModelProperty.Name).GetValue(this));
}
referenceModel = (ModelAllPrivateSetArrayOfNullableChild1)referenceModel.GetType().GetMethod("DeepClone").Invoke(referenceModel, new object[0]);
var thisModelProperties = this.GetType().GetProperties();
var result = A.Dummy<ModelCloningPrivateSetArrayOfNullableChild1>();
foreach (var thisModelProperty in thisModelProperties)
{
thisModelProperty.DeclaringType.GetProperty(thisModelProperty.Name).SetValue(result, referenceModel.GetType().GetProperty(thisModelProperty.Name).GetValue(referenceModel));
}
return result;
}
}
} | 60.191011 | 267 | 0.725873 | [
"MIT"
] | OBeautifulCode/OBeautifulCode.CodeGen | OBeautifulCode.CodeGen.ModelObject.Test/Models/Scripted/Cloning/PrivateSet/ArrayOfNullable/ModelCloningPrivateSetArrayOfNullableChild1.cs | 10,716 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GoalLine.Data;
using GoalLine.Structures;
namespace GoalLine.Processes.ProcessLogic
{
class AITeamAndTactics
{
private class AvailablePlayer
{
public int PlayerID { get; set; }
public PlayerPosition Pos { get; set; }
public PlayerPositionSide Side { get; set; }
public int Rating { get; set; }
}
/// <summary>
/// Return a list of all eligible players for this match
/// </summary>
/// <param name="t">Team object</param>
/// <param name="f">Fixture object</param>
/// <returns>List of </returns>
private List<AvailablePlayer> GetEligiblePlayers(Team t, Fixture f)
{
List<AvailablePlayer> retVal = new List<AvailablePlayer>();
PlayerAdapter pa = new PlayerAdapter();
List<Player> players = pa.GetPlayers(t.UniqueID);
foreach (Player p in players)
{
// TODO: When we have injuries, remember to deal with these appropriately.
AvailablePlayer ap = new AvailablePlayer();
ap.PlayerID = p.UniqueID;
ap.Pos = p.Position;
ap.Side = p.PreferredSide;
ap.Rating = p.OverallRating;
retVal.Add(ap);
}
return retVal;
}
/// <summary>
/// Loop round all AI teams, and select a team appropriate to play the fixture.
/// </summary>
public void SelectTeamIfPlaying()
{
FixtureAdapter fa = new FixtureAdapter();
WorldAdapter wa = new WorldAdapter();
TeamAdapter ta = new TeamAdapter();
ManagerAdapter ma = new ManagerAdapter();
List<Fixture> AllFixtures = fa.GetFixtures(wa.CurrentDate);
int TESTf = 0;
foreach (Fixture f in AllFixtures)
{
TESTf++;
Debug.Print("Fixture " + f.ToString());
for (int t = 0; t <= 1; t++)
{
Team ThisTeam = ta.GetTeam(f.TeamIDs[t]);
Manager M = ma.GetManager(ThisTeam.ManagerID);
if (!M.Human)
{
Team Opposition = ta.GetTeam(f.TeamIDs[1 - t]);
PlayerAdapter pa = new PlayerAdapter();
int[,] PlayerGridPositions = new int[5, 8]; // TODO: Maybe not hard code these...
for (int x = 0; x <= PlayerGridPositions.GetUpperBound(0); x++)
for (int y = 0; y <= PlayerGridPositions.GetUpperBound(1); y++)
PlayerGridPositions[x, y] = -1;
Formation TeamFormation = new FormationAdapter().GetFormation(ThisTeam.CurrentFormation);
List<AvailablePlayer> avail = GetEligiblePlayers(ThisTeam, f);
foreach (Point2 point in TeamFormation.Points)
{
AvailablePlayer SelPlayer = FindBestPlayerForPosition(point, avail);
if(SelPlayer == null)
{
throw new Exception("Unable to find a player for this position");
}
PlayerGridPositions[point.X, point.Y] = SelPlayer.PlayerID;
avail.Remove(SelPlayer);
}
ta.SavePlayerFormation(ThisTeam.UniqueID, TeamFormation.UniqueID, PlayerGridPositions);
}
}
}
}
private AvailablePlayer FindBestPlayerForPosition(Point2 GridPos, List<AvailablePlayer> avail)
{
PlayerAdapter pa = new PlayerAdapter();
FormationAdapter fa = new FormationAdapter();
SuitablePlayerInfo suit = fa.SuitablePlayerPositions(GridPos);
AvailablePlayer best = null;
foreach(PlayerPosition pos in suit.Positions)
{
foreach(PlayerPositionSide side in suit.Sides)
{
best = (from ap in avail
where ap.Side == side && ap.Pos == pos
select ap).FirstOrDefault();
if (best != null)
break;
}
if(best != null)
break;
}
if(best == null)
{
best = (from ap in avail
orderby ap.Rating descending
select ap).FirstOrDefault();
}
return best;
}
}
}
| 34.577465 | 113 | 0.497352 | [
"MIT"
] | meesterturner/GoalLine | GoalLine.Processes/ProcessLogic/AITeamAndTactics.cs | 4,912 | C# |
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia
namespace EtAlii.Ubigia.Api.Transport.Management.SignalR
{
using EtAlii.Ubigia.Api.Transport.SignalR;
using EtAlii.xTechnology.MicroContainer;
internal class SignalRStorageClientsScaffolding : IScaffolding
{
public void Register(IRegisterOnlyContainer container)
{
container.Register<IStorageConnection, SignalRStorageConnection>();
container.Register<IHubProxyMethodInvoker, HubProxyMethodInvoker>();
container.Register<IAuthenticationManagementDataClient, SignalRAuthenticationManagementDataClient>();
container.Register<ISignalRAuthenticationTokenGetter, SignalRAuthenticationTokenGetter>();
container.Register<IInformationDataClient, SignalRInformationDataClient>();
container.Register<IStorageDataClient, SignalRStorageDataClient>();
container.Register<IAccountDataClient, SignalRAccountDataClient>();
container.Register<ISpaceDataClient, SignalRSpaceDataClient>();
// No Notification clients yet.
container.Register<IStorageNotificationClient, StorageNotificationClientStub>();
container.Register<IAccountNotificationClient, AccountNotificationClientStub>();
container.Register<ISpaceNotificationClient, SpaceNotificationClientStub>();
}
}
}
| 46.967742 | 113 | 0.745192 | [
"MIT"
] | vrenken/EtAlii.Ubigia | Source/Api/EtAlii.Ubigia.Api.Transport.Management.SignalR/_Scaffolding/SignalRStorageClientsScaffolding.cs | 1,458 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.ApplicationModel.Contacts;
namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario1_CreateContacts : Page
{
private MainPage rootPage = MainPage.Current;
public Scenario1_CreateContacts()
{
this.InitializeComponent();
}
private async Task<ContactList> _GetContactList()
{
ContactStore store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
if (null == store)
{
rootPage.NotifyUser("Unable to get a contacts store.", NotifyType.ErrorMessage);
return null;
}
ContactList contactList;
IReadOnlyList<ContactList> contactLists = await store.FindContactListsAsync();
if (0 == contactLists.Count)
{
contactList = await store.CreateContactListAsync("TestContactList");
}
else
{
contactList = contactLists[0];
}
return contactList;
}
private async Task<ContactAnnotationList> _GetContactAnnotationList()
{
ContactAnnotationStore annotationStore = await ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite);
if (null == annotationStore)
{
rootPage.NotifyUser("Unable to get an annotations store.", NotifyType.ErrorMessage);
return null;
}
ContactAnnotationList annotationList;
IReadOnlyList<ContactAnnotationList> annotationLists = await annotationStore.FindAnnotationListsAsync();
if (0 == annotationLists.Count)
{
annotationList = await annotationStore.CreateAnnotationListAsync();
}
else
{
annotationList = annotationLists[0];
}
return annotationList;
}
private async void CreateTestContacts()
{
//
// Creating two test contacts with email address and phone number.
//
Contact contact1 = new Contact();
contact1.FirstName = "TestContact1";
ContactEmail email1 = new ContactEmail();
email1.Address = "[email protected]";
contact1.Emails.Add(email1);
ContactPhone phone1 = new ContactPhone();
phone1.Number = "4255550100";
contact1.Phones.Add(phone1);
Contact contact2 = new Contact();
contact2.FirstName = "TestContact2";
ContactEmail email2 = new ContactEmail();
email2.Address = "[email protected]";
email2.Kind = ContactEmailKind.Other;
contact2.Emails.Add(email2);
ContactPhone phone2 = new ContactPhone();
phone2.Number = "4255550101";
phone2.Kind = ContactPhoneKind.Mobile;
contact2.Phones.Add(phone2);
// Save the contacts
ContactList contactList = await _GetContactList();
if (null == contactList)
{
return;
}
await contactList.SaveContactAsync(contact1);
await contactList.SaveContactAsync(contact2);
//
// Create annotations for those test contacts.
// Annotation is the contact meta data that allows People App to generate deep links
// in the contact card that takes the user back into this app.
//
ContactAnnotationList annotationList = await _GetContactAnnotationList();
if (null == annotationList)
{
return;
}
ContactAnnotation annotation = new ContactAnnotation();
annotation.ContactId = contact1.Id;
// Remote ID: The identifier of the user relevant for this app. When this app is
// launched into from the People App, this id will be provided as context on which user
// the operation (e.g. ContactProfile) is for.
annotation.RemoteId = "user12";
// The supported operations flags indicate that this app can fulfill these operations
// for this contact. These flags are read by apps such as the People App to create deep
// links back into this app. This app must also be registered for the relevant
// protocols in the Package.appxmanifest (in this case, ms-contact-profile).
annotation.SupportedOperations = ContactAnnotationOperations.ContactProfile;
if (!await annotationList.TrySaveAnnotationAsync(annotation))
{
rootPage.NotifyUser("Failed to save annotation for TestContact1 to the store.", NotifyType.ErrorMessage);
return;
}
annotation = new ContactAnnotation();
annotation.ContactId = contact2.Id;
annotation.RemoteId = "user22";
// You can also specify multiple supported operations for a contact in a single
// annotation. In this case, this annotation indicates that the user can be
// communicated via VOIP call, Video Call, or IM via this application.
annotation.SupportedOperations = ContactAnnotationOperations.Message |
ContactAnnotationOperations.AudioCall |
ContactAnnotationOperations.VideoCall;
if (!await annotationList.TrySaveAnnotationAsync(annotation))
{
rootPage.NotifyUser("Failed to save annotation for TestContact2 to the store.", NotifyType.ErrorMessage);
return;
}
rootPage.NotifyUser("Sample data created successfully.", NotifyType.StatusMessage);
}
private async void DeleteTestContacts()
{
ContactList contactList = null;
ContactStore store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
if (null != store)
{
IReadOnlyList<ContactList> contactLists = await store.FindContactListsAsync();
if (0 < contactLists.Count)
{
contactList = contactLists[0];
}
}
if (null != contactList)
{
await contactList.DeleteAsync();
rootPage.NotifyUser("Sample data deleted.", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Could not delete sample data.", NotifyType.ErrorMessage);
}
}
}
}
| 37.888325 | 160 | 0.593917 | [
"MIT"
] | 544146/Windows-universal-samples | Samples/ContactCardIntegration/cs/Scenario1_CreateContacts.xaml.cs | 7,464 | C# |
Subsets and Splits