Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Count() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
9441 Examples
19
Source : Watchdog.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
private void WatchdogWorkerRoutine(object obj)
{
WatchdogState ws = (WatchdogState)obj;
IEnumerable<Process> stillWorkingList;
if (ws.IsFirstTaken)
{
SnapshotProcesses(ws.SecondSnapshot);
stillWorkingList = Intersect(ws);
if (stillWorkingList != null)
{
Log.Warning("There is {0} process(es) being hung",stillWorkingList.Count());
KillList(stillWorkingList);
}
else
Log.Info("There is no hang process.");
ws.Release();
ws = null;
}
}
19
Source : MelonMain.cs
with GNU General Public License v3.0
from 1330-Studios
with GNU General Public License v3.0
from 1330-Studios
internal void Set(bool val = false) {
#if AGGRESSIVE_TACTICS
//IL2CPP.ResolveICall<intIntPtrDelegate>("UnityEngine.QualitySettings::set_vSyncCount")(0);
var mods = AppDomain.CurrentDomain.Getreplacedemblies();
GC = GCTime();
MelonCoroutines.Start(GC);
#else
var mods = MelonHandler.Mods.Select(a=>a.replacedembly).ToArray();
#endif
if (!val) return;
var sw = new Stopwatch();
sw.Start();
var methodCount = 0;
#region RuntimeHelpers
for (var i = 0; i < mods.Count(); i++) {
var asm = mods[i];
var types = asm.GetTypes();
for (var j = 0; j < types.Length; j++)
try {
var type = types[j];
var methods = AccessTools.GetDeclaredMethods(type);
for (var k = 0; k < methods.Count; k++) {
RuntimeHelpers.PrepareMethod(methods[k].MethodHandle);
methodCount += 1;
}
} catch {}
}
#endregion
sw.Stop();
MelonLogger.Msg($"Optimized {methodCount:N0} methods in {sw.Elapsed.Milliseconds:N0} milliseconds!");
}
19
Source : IrdTests.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
[Test, Explicit("Requires custom data")]
public async Task TocSizeTest()
{
var path = @"E:\FakeCDs\PS3 Games\ird";
var result = new List<(string filename, long size)>();
foreach (var f in Directory.EnumerateFiles(path, "*.ird", SearchOption.TopDirectoryOnly))
{
var bytes = await File.ReadAllBytesAsync(f).ConfigureAwait(false);
var ird = IrdParser.Parse(bytes);
using (var header = GetDecompressHeader(ird))
result.Add((Path.GetFileName(f), header.Length));
}
replacedert.That(result.Count, Is.GreaterThan(0));
var groupedStats = (from t in result
group t by t.size into g
select new {size = g.Key, count = g.Count()}
).OrderByDescending(i => i.count)
.ThenByDescending(i => i.size)
.ToList();
var largest = groupedStats.Max(i => i.size);
var largesreplacedem = result.First(i => i.size == largest);
Console.WriteLine($"Largest TOC: {largesreplacedem.filename} ({largest.replacedtorageUnit()})");
foreach (var s in groupedStats)
Console.WriteLine($"{s.count} items of size {s.size}");
replacedert.That(groupedStats.Count, Is.EqualTo(1));
}
19
Source : DbContext.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
{
var dbParameters = new List<IDbDataParameter>();
cmd.Transaction = _transaction;
cmd.CommandText = sql;
if (commandTimeout.HasValue)
{
cmd.CommandTimeout = commandTimeout.Value;
}
if (commandType.HasValue)
{
cmd.CommandType = commandType.Value;
}
if (parameter is IDbDataParameter)
{
dbParameters.Add(parameter as IDbDataParameter);
}
else if (parameter is IEnumerable<IDbDataParameter> parameters)
{
dbParameters.AddRange(parameters);
}
else if (parameter is Dictionary<string, object> keyValues)
{
foreach (var item in keyValues)
{
var param = CreateParameter(cmd, item.Key, item.Value);
dbParameters.Add(param);
}
}
else if (parameter != null)
{
var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
var values = handler(parameter);
foreach (var item in values)
{
var param = CreateParameter(cmd, item.Key, item.Value);
dbParameters.Add(param);
}
}
if (dbParameters.Count > 0)
{
foreach (IDataParameter item in dbParameters)
{
if (item.Value == null)
{
item.Value = DBNull.Value;
}
var pattern = $@"in\s+([\@,\:,\?]?{item.ParameterName})";
var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
{
var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
var list = new List<object>();
if (item.Value is IEnumerable<object> || item.Value is Array)
{
list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
}
else
{
list.Add(item.Value);
}
if (list.Count() > 0)
{
cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
foreach (var iitem in list)
{
var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
var param = CreateParameter(cmd, key, iitem);
cmd.Parameters.Add(param);
}
}
else
{
cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
}
}
else
{
cmd.Parameters.Add(item);
}
}
}
if (Logging != null)
{
var parameters = new Dictionary<string, object>();
foreach (IDbDataParameter item in cmd.Parameters)
{
parameters.Add(item.ParameterName, item.Value);
}
Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
}
}
19
Source : DbQueryAsync.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
public async Task<int> InsertAsync(IEnumerable<T> enreplacedys, int? commandTimeout = null)
{
if (enreplacedys == null || enreplacedys.Count() == 0)
{
return 0;
}
var sql = ResovleBatchInsert(enreplacedys);
return await _context.ExecuteAsync(sql, _parameters, commandTimeout);
}
19
Source : DbQuerySync.cs
with Apache License 2.0
from 1448376744
with Apache License 2.0
from 1448376744
public int Insert(IEnumerable<T> enreplacedys, int? commandTimeout = null)
{
if (enreplacedys==null || enreplacedys.Count()==0)
{
return 0;
}
var sql = ResovleBatchInsert(enreplacedys);
return _context.Execute(sql, _parameters, commandTimeout);
}
19
Source : GeneratorClass.cs
with MIT License
from 188867052
with MIT License
from 188867052
public static string GenerateRoutes(IEnumerable<RouteInfo> infos)
{
StringBuilder sb = new StringBuilder();
var group = infos.GroupBy(o => o.Namespace);
sb.AppendLine($"using {typeof(object).Namespace};");
sb.AppendLine($"using {typeof(Dictionary<int, int>).Namespace};");
sb.AppendLine();
for (int i = 0; i < group.Count(); i++)
{
sb.Append(GenerateNamespace(group.ElementAt(i), i == (group.Count() - 1)));
}
return sb.ToString();
}
19
Source : GeneratorClass.cs
with MIT License
from 188867052
with MIT License
from 188867052
private static StringBuilder GenerateNamespace(IGrouping<string, RouteInfo> namespaceGroup, bool isLast)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"namespace {GetConvertedNamespace(namespaceGroup.Key)}");
sb.AppendLine("{");
var group = namespaceGroup.GroupBy(o => o.ControllerName);
for (int i = 0; i < group.Count(); i++)
{
sb.Append(GenerateClreplaced(group.ElementAt(i), i == (group.Count() - 1)));
}
sb.AppendLine("}");
if (!isLast)
{
sb.AppendLine();
}
return sb;
}
19
Source : GeneratorClass.cs
with MIT License
from 188867052
with MIT License
from 188867052
private static StringBuilder GenerateClreplaced(IGrouping<string, RouteInfo> group, bool isLast)
{
string clreplacedFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller";
string crefNamespace = GetCrefNamespace(clreplacedFullName, GetConvertedNamespace(group.First().Namespace));
StringBuilder sb = new StringBuilder();
sb.AppendLine($" /// <summary>");
sb.AppendLine($" /// <see cref=\"{crefNamespace}\"/>");
sb.AppendLine($" /// </summary>");
sb.AppendLine($" public clreplaced {group.Key}Route");
sb.AppendLine(" {");
for (int i = 0; i < group.Count(); i++)
{
var item = group.ElementAt(i);
var renamedAction = RenameOverloadedAction(group, i);
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public const string {renamedAction} = \"{item.Path}\";");
if (i != group.Count() - 1)
{
sb.AppendLine();
}
}
sb.AppendLine(" }");
if (!isLast)
{
sb.AppendLine();
}
return sb;
}
19
Source : GeneratorClass.cs
with MIT License
from 188867052
with MIT License
from 188867052
private static string RenameOverloadedAction(IGrouping<string, RouteInfo> group, int index)
{
var currenreplacedem = group.ElementAt(index);
var sameActionNameGroup = group.GroupBy(o => o.ActionName);
foreach (var item in sameActionNameGroup)
{
if (item.Count() > 1)
{
for (int i = 1; i < item.Count(); i++)
{
var element = item.ElementAt(i);
if (element == currenreplacedem)
{
return element.ActionName + i;
}
}
}
}
return currenreplacedem.ActionName;
}
19
Source : RouteGenerator.cs
with MIT License
from 188867052
with MIT License
from 188867052
private static StringBuilder GenerateClreplaced(IGrouping<string, RouteInfo> group, bool isLast)
{
string clreplacedFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller";
string crefNamespace = GetCrefNamespace(clreplacedFullName, GetConvertedNamespace(group.First().Namespace));
StringBuilder sb = new StringBuilder();
sb.AppendLine($" /// <summary>");
sb.AppendLine($" /// <see cref=\"{crefNamespace}\"/>");
sb.AppendLine($" /// </summary>");
sb.AppendLine($" public clreplaced {group.Key}Route");
sb.AppendLine(" {");
for (int i = 0; i < group.Count(); i++)
{
var item = group.ElementAt(i);
var renamedAction = RenameOverloadedAction(group, i);
sb.AppendLine(" /// <summary>");
sb.AppendLine($" /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>");
sb.AppendLine(" /// </summary>");
sb.AppendLine($" public const string {renamedAction} = \"{item.Path}\";");
if (config != null && config.GenerateMethod)
{
sb.AppendLine($" public static async Task<T> {item.ActionName}Async<T>({GeneraParameters(item.Parameters, true, false)})");
sb.AppendLine(" {");
sb.AppendLine($" var routeInfo = new {nameof(RouteInfo)}");
sb.AppendLine(" {");
sb.AppendLine($" {nameof(RouteInfo.HttpMethods)} = \"{item.HttpMethods}\",");
sb.AppendLine($" {nameof(RouteInfo.Path)} = {renamedAction},");
sb.Append(GenerateParameters(item.Parameters));
sb.AppendLine(" };");
sb.AppendLine($" return await {nameof(HttpClientAsync)}.{nameof(HttpClientAsync.Async)}<T>(routeInfo{GeneraParameters(item.Parameters, false, true)});");
sb.AppendLine(" }");
}
if (i != group.Count() - 1)
{
sb.AppendLine();
}
}
sb.AppendLine(" }");
if (!isLast)
{
sb.AppendLine();
}
return sb;
}
19
Source : RouteGenerator.cs
with MIT License
from 188867052
with MIT License
from 188867052
public static string GenerateRoutes(IList<RouteInfo> infos)
{
StringBuilder sb = new StringBuilder();
var group = infos.GroupBy(o => o.Namespace);
sb.AppendLine($"using {typeof(object).Namespace};");
sb.AppendLine($"using {typeof(Dictionary<int, int>).Namespace};");
sb.AppendLine($"using {typeof(Task).Namespace};");
sb.AppendLine($"using {typeof(HttpClientAsync).Namespace};");
sb.AppendLine();
for (int i = 0; i < group.Count(); i++)
{
sb.Append(GenerateNamespace(group.ElementAt(i), i == (group.Count() - 1)));
}
return sb.ToString();
}
19
Source : VerifyHelper.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static void IsDict<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> dict, IEnumerable<KeyValuePair<TKey, TValue>> dict1)
{
IDictionary<TKey, TValue> d1 = new Dictionary<TKey, TValue>(dict.ToIDict());
var d2 = new Dictionary<TKey, TValue>(dict1.ToIDict());
replacedert.Equal(d1.Count, d2.Count());
foreach (var item in d2)
{
replacedert.Contains(item.Key, d1);
item.Value.Is(d1[item.Key]);
}
}
19
Source : BuildWindow.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
void DrawQuickStart()
{
GUILayout.BeginVertical();
GUILayout.Label("Quick Start", EditorStyles.boldLabel);
var entryCount = quickstartData.clientCount + 1;
// Make sure we have enough entries
var minEntryCount = Math.Max(entryCount, 2);
while (minEntryCount > quickstartData.entries.Count())
quickstartData.entries.Add(new QuickstartEntry());
string str = "Starting Game - Server (Headless) & " + quickstartData.clientCount.ToString() + " clients";
GUILayout.Label(str, EditorStyles.boldLabel);
Color defaultGUIBackgrounColor = GUI.backgroundColor;
// Quick start buttons
GUILayout.BeginHorizontal();
{
GUI.backgroundColor = Color.green;
if (GUILayout.Button("Start"))
{
for (int i = 0; i < entryCount; i++)
{
if (quickstartData.entries[i].runInEditor)
continue;
//EditorLevelManager.StartGameInEditor();
else
{
RunBuild(quickstartData.entries[i].gameLoopMode);
}
}
}
GUI.backgroundColor = defaultGUIBackgrounColor;
GUI.backgroundColor = Color.red;
if (GUILayout.Button("Stop All"))
{
StopAll();
}
GUI.backgroundColor = defaultGUIBackgrounColor;
}
GUILayout.EndHorizontal();
// Settings
EditorGUI.BeginChangeCheck();
quickstartData.clientCount = EditorGUILayout.IntField("Clients", quickstartData.clientCount);
quickstartData.editorRole = (EditorRole)EditorGUILayout.EnumPopup("Use Editor as", quickstartData.editorRole);
quickstartData.entries[0].gameLoopMode = GameLoopMode.Server;
quickstartData.entries[0].headless = quickstartData.headlessServer;
quickstartData.entries[0].runInEditor = quickstartData.editorRole == EditorRole.Server;
quickstartData.entries[1].runInEditor = quickstartData.editorRole == EditorRole.Client;
for (var i = 1; i < entryCount; i++)
{
quickstartData.entries[i].gameLoopMode = GameLoopMode.Client;
quickstartData.entries[i].headless = false;
}
// Draw entries
GUILayout.Label("Started processes:");
for (var i = 0; i < entryCount; i++)
{
var entry = quickstartData.entries[i];
GUILayout.BeginVertical();
{
GUILayout.BeginHorizontal();
{
GUILayout.Space(20);
GUILayout.Label("- Stand Alone Build", GUILayout.Width(130));
EditorGUILayout.SelectableLabel(entry.gameLoopMode.ToString(), EditorStyles.textField, GUILayout.Height(EditorGUIUtility.singleLineHeight));
}
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
}
GUILayout.EndVertical();
}
19
Source : VerifyHelper.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static void IsMap(this IEnumerable<KeyValuePair<string, object>> dict, BssomMap map)
{
replacedert.Equal(dict.Count(), map.Count);
foreach (var item in dict)
{
replacedert.Contains(item.Key, map);
item.Value.Is(map[item.Key]);
}
}
19
Source : X86Assembly.cs
with MIT License
from 20chan
with MIT License
from 20chan
public static string FromInline(ASM inst, IEnumerable<object> parameters)
{
return parameters.Count() == 0 ? inst.ToString() : $"{inst} {string.Join(", ", parameters)}";
}
19
Source : JcApiHelper_InitParam.cs
with MIT License
from 279328316
with MIT License
from 279328316
private static ParamModel GetParam(FieldInfo fi, int index = 0)
{
PTypeModel ptype = GetPType(fi.FieldType);
int? value = null;
if (fi.FieldType.IsEnum)
{
try
{
value = Convert.ToInt32(Enum.Parse(fi.FieldType, fi.Name));
}
catch
{ //如转换失败,忽略不做处理
}
}
string fiId = null;
if (fi.DeclaringType != null)
{
fiId = $"F:{fi.DeclaringType.ToString()}.{fi.Name}";
}
ParamModel param = new ParamModel()
{
Name = fi.Name,
Id = fiId,
PType = ptype,
ParamValue = value,
CustomAttrList = fi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
Position = index + 1
};
if (fi.CustomAttributes.Count() > 0)
{
}
return param;
}
19
Source : JcApiHelper_InitParam.cs
with MIT License
from 279328316
with MIT License
from 279328316
private static ParamModel GetParam(PropertyInfo pi, int index = 0)
{
PTypeModel ptype = GetPType(pi.PropertyType);
string piId = null;
if (pi.DeclaringType != null)
{
string declaringTypeName = pi.DeclaringType.ToString();
if (declaringTypeName.IndexOf("`") != -1)
{ //泛型属性Id结构如下:P:Jc.Core.Robj`1.Result
declaringTypeName = declaringTypeName.Substring(0, declaringTypeName.IndexOf("`") + 2);
}
piId = $"P:{declaringTypeName}.{pi.Name}";
}
ParamModel param = new ParamModel()
{
Name = pi.Name,
Id = piId,
PType = ptype,
CustomAttrList = pi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
Position = index + 1
};
if(pi.CustomAttributes.Count()>0)
{
}
return param;
}
19
Source : Resp3HelperTests.cs
with MIT License
from 2881099
with MIT License
from 2881099
[Fact]
public void AclCat()
{
var replacedertList = new[] { "keyspace", "read", "write", "set", "sortedset", "list", "hash", "string", "bitmap", "hyperloglog", "geo", "stream", "pubsub", "admin", "fast", "slow", "blocking", "dangerous", "connection", "transaction", "scripting" };
var rt = rds.AclCat();
if (!rt.IsError) replacedertList.Where(a => rt.Value.Contains(a)).Count().replacedertEqual(replacedertList.Length);
replacedertList = new[] { "flushdb", "lastsave", "info", "latency", "slowlog", "replconf", "slaveof", "acl", "flushall", "role", "pfdebug", "cluster", "shutdown", "restore-asking", "sort", "sync", "pfselftest", "restore", "swapdb", "config", "keys", "psync", "migrate", "bgsave", "monitor", "bgrewriteaof", "module", "debug", "save", "client", "replicaof" };
rt = rds.AclCat("dangerous");
if (!rt.IsError) replacedertList.Where(a => rt.Value.Contains(a)).Count().replacedertEqual(replacedertList.Length);
}
19
Source : DbSetAsync.cs
with MIT License
from 2881099
with MIT License
from 2881099
async public Task AddRangeAsync(IEnumerable<TEnreplacedy> data) {
if (CanAdd(data, true) == false) return;
if (data.ElementAtOrDefault(1) == default(TEnreplacedy)) {
await AddAsync(data.First());
return;
}
if (_tableIdenreplacedys.Length > 0) {
//有自增,马上执行
switch (_fsql.Ado.DataType) {
case DataType.SqlServer:
case DataType.PostgreSQL:
await DbContextExecCommandAsync();
var rets = await this.OrmInsert(data).ExecuteInsertedAsync();
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
var idx = 0;
foreach (var s in data)
_fsql.MapEnreplacedyValue(_enreplacedyType, rets[idx++], s);
IncrAffrows(rets.Count);
AttachRange(rets);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
await AddOrUpdateNavigateListAsync(item);
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
foreach (var s in data)
await AddPrivAsync(s, false);
return;
}
} else {
//进入队列,等待 SaveChanges 时执行
foreach (var item in data)
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEnreplacedyState(item));
AttachRange(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
await AddOrUpdateNavigateListAsync(item);
}
}
19
Source : CommandFlagsTests.cs
with MIT License
from 2881099
with MIT License
from 2881099
[Fact]
public void Test01()
{
var methodsCount = typeof(RedisClient).GetMethods().Count();
}
19
Source : DbSetSync.cs
with MIT License
from 2881099
with MIT License
from 2881099
public void AddRange(IEnumerable<TEnreplacedy> data) {
if (CanAdd(data, true) == false) return;
if (data.ElementAtOrDefault(1) == default(TEnreplacedy)) {
Add(data.First());
return;
}
if (_tableIdenreplacedys.Length > 0) {
//有自增,马上执行
switch (_fsql.Ado.DataType) {
case DataType.SqlServer:
case DataType.PostgreSQL:
DbContextExecCommand();
var rets = this.OrmInsert(data).ExecuteInserted();
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
var idx = 0;
foreach (var s in data)
_fsql.MapEnreplacedyValue(_enreplacedyType, rets[idx++], s);
IncrAffrows(rets.Count);
AttachRange(rets);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
AddOrUpdateNavigateList(item);
return;
case DataType.MySql:
case DataType.Oracle:
case DataType.Sqlite:
foreach (var s in data)
AddPriv(s, false);
return;
}
} else {
//进入队列,等待 SaveChanges 时执行
foreach (var item in data)
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEnreplacedyState(item));
AttachRange(data);
if (_ctx.Options.EnableAddOrUpdateNavigateList)
foreach (var item in data)
AddOrUpdateNavigateList(item);
}
}
19
Source : PackagesConfigLocatorTest.cs
with MIT License
from 3F
with MIT License
from 3F
[Theory]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfig)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfig)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfig)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfig)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfigSolution)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfigSolution)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfigSolution)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfigSolution)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfigLegacy)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfigLegacy)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfigLegacy)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfigLegacy)]
public void FindAndLoadTest1(string file, SlnItems items)
{
using Sln sln = new(file, items);
IEnumerable<PackagesConfig> pkgs = PackagesConfigLocator.FindAndLoadConfigs(sln.Result, sln.Result.ResultType);
replacedert.Equal(sln.Result.PackagesConfigs.Count(), pkgs.Count());
int idx = 0;
foreach(var config in sln.Result.PackagesConfigs)
{
replacedert.Equal(config.Packages, pkgs.ElementAt(idx++).Packages);
}
}
19
Source : PackagesConfigLocatorTest.cs
with MIT License
from 3F
with MIT License
from 3F
[Theory]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfig)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfig)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfig)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfig)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfigSolution)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfigSolution)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfigSolution)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfigSolution)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\1\test.sln", SlnItems.PackagesConfigLegacy)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\2\test.sln", SlnItems.PackagesConfigLegacy)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\3\test.sln", SlnItems.PackagesConfigLegacy)]
[InlineData(TestData.ROOT + @"PackagesConfig\sln\4\test.sln", SlnItems.PackagesConfigLegacy)]
public void FindTest1(string file, SlnItems items)
{
using Sln sln = new(file, items);
IEnumerable<string> pkgs = PackagesConfigLocator.FindConfigs(sln.Result, sln.Result.ResultType);
replacedert.Equal(sln.Result.PackagesConfigs.Count(), pkgs.Count());
int idx = 0;
foreach(var config in sln.Result.PackagesConfigs)
{
replacedert.Equal(config.File, pkgs.ElementAt(idx++));
}
}
19
Source : PersonFuzzerWithPasswordShould.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
[TestCase(500)]
public void GeneratePreplacedwords_of_various_sizes(int attempts)
{
var fuzzer = new Fuzzer();
var generatedPreplacedwords = new List<string>();
for (var i = 0; i < attempts; i++)
{
generatedPreplacedwords.Add(fuzzer.GeneratePreplacedword());
}
var generatedSizes = generatedPreplacedwords.Select(p => p.Length).Distinct();
Check.That(generatedSizes.Count()).IsStrictlyGreaterThan(2);
}
19
Source : Row.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public SeatingOptionSuggested SuggestSeatingOption(SuggestionRequest suggestionRequest)
{
var seatingOptionSuggested = new SeatingOptionSuggested(suggestionRequest);
var availableSeatsCompliant = Seats.SelectAvailableSeatsCompliant(suggestionRequest.PricingCategory);
var rowSize = Seats.Count();
var adjacentSeatsOfExpectedSize = availableSeatsCompliant.SelectAdjacentSeats(suggestionRequest.PartyRequested);
var adjacentSeatsOrdered = adjacentSeatsOfExpectedSize.OrderByMiddleOfTheRow(rowSize);
foreach (var adjacentSeats in adjacentSeatsOrdered)
{
seatingOptionSuggested.AddSeats(adjacentSeats);
if (seatingOptionSuggested.MatchExpectation())
{
return seatingOptionSuggested;
}
}
return new SeatingOptionNotAvailable(suggestionRequest);
}
19
Source : UnityARBuildPostprocessor.cs
with MIT License
from 734843327
with MIT License
from 734843327
internal static bool ReplaceCppMacro(string[] lines, string name, string newValue)
{
bool replaced = false;
Regex matchRegex = new Regex(@"^.*#\s*define\s+" + name);
Regex replaceRegex = new Regex(@"^.*#\s*define\s+" + name + @"(:?|\s|\s.*[^\\])$");
for (int i = 0; i < lines.Count(); i++)
{
if (matchRegex.Match (lines [i]).Success) {
lines [i] = replaceRegex.Replace (lines [i], "#define " + name + " " + newValue);
replaced = true;
}
}
return replaced;
}
19
Source : Geometry.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
public static Polyline[] Offset(this IEnumerable<Polyline> polylines, double distance) {
Polyline[] polylinesOffset = new Polyline[polylines.Count()];
if (distance != 0) {
List<Polyline> c0;
List<Polyline> c1;
int i = 0;
foreach(Polyline p in polylines) {
Geometry.Polyline3D.Offset(p, Math.Abs(distance), out c0, out c1);
if (distance < 0) {
polylinesOffset[i]=(c1[0]);
} else {
polylinesOffset[i] = (c0[0]);
}
i++;
}
return polylinesOffset;
}
return polylines.ToArray();
}
19
Source : GH_Cloud.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
private void ResolveDisplay() {
Random random = new Random();
this.DisplayCloud = null;
this.DisplayCloud = new PointCloud();
if (this.m_value.Count < 1000) {
this.DisplayCloud.AddRange(this.m_value.GetPoints());
return;
}
int count = checked(this.m_value.Count - 1);
for (int i = 0; i <= count; i = checked(i + 1000)) {
long num = (long)random.Next(0, checked(this.m_value.Count() - 1));
this.DisplayCloud.Add(this.m_value[checked((int)num)].Location);
this.DisplayCloud[checked(this.DisplayCloud.Count() - 1)].Color = (this.m_value[checked((int)num)].Color);
}
}
19
Source : NhentaiHelper.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
public static string GetExt(string imgUrl)
{
string[] splits = imgUrl.Split('.');
return splits[splits.Count() - 1];
}
19
Source : RpcService.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
internal void CleanupRegistration()
{
foreach (var controller in Controllers)
{
var gps = controller.Value.GroupBy(m => m.MethodName).Where(gp => gp.Count() > 1);
var hiddenMethods = new List<RpcMethod>();
foreach (var gp in gps)
{
hiddenMethods.AddRange(gp.Where(m => m.Method.DeclaringType != controller.Key));
}
foreach (var m in hiddenMethods)
{
controller.Value.Remove(m);
}
}
}
19
Source : LUTPanelOptions.cs
with MIT License
from a1xd
with MIT License
from a1xd
private static (Vec2<float>[], int length) UserTextToPoints(string userText)
{
if (string.IsNullOrWhiteSpace(userText))
{
throw new ApplicationException("Text must be entered in text box to fill Look Up Table.");
}
Vec2<float>[] points = new Vec2<float>[AccelArgs.MaxLutPoints];
var userTextSplit = userText.Trim().Trim(';').Split(';');
int index = 0;
float lastX = 0;
int pointsCount = userTextSplit.Count();
if (pointsCount < 2)
{
throw new ApplicationException("At least 2 points required");
}
if (pointsCount > AccelArgs.MaxLutPoints)
{
throw new ApplicationException($"Number of points exceeds max ({AccelArgs.MaxLutPoints})");
}
foreach(var pointEntry in userTextSplit)
{
var pointSplit = pointEntry.Trim().Split(',');
if (pointSplit.Length != 2)
{
throw new ApplicationException($"Point at index {index} is malformed. Expected format: x,y; Given: {pointEntry.Trim()}");
}
float x;
float y;
try
{
x = float.Parse(pointSplit[0]);
}
catch (Exception ex)
{
throw new ApplicationException($"X-value for point at index {index} is malformed. Expected: float. Given: {pointSplit[0]}", ex);
}
if (x <= 0)
{
throw new ApplicationException($"X-value for point at index {index} is less than or equal to 0. Point (0,0) is implied and should not be specified in points text.");
}
if (x <= lastX)
{
throw new ApplicationException($"X-value for point at index {index} is less than or equal to previous x-value. Value: {x} Previous: {lastX}");
}
lastX = x;
try
{
y = float.Parse(pointSplit[1]);
}
catch (Exception ex)
{
throw new ApplicationException($"Y-value for point at index {index} is malformed. Expected: float. Given: {pointSplit[1]}", ex);
}
if (y <= 0)
{
throw new ApplicationException($"Y-value for point at index {index} is less than or equal to 0. Value: {y}");
}
points[index] = new Vec2<float> { x = x, y = y };
index++;
}
return (points, userTextSplit.Length);
}
19
Source : Brain.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public Dictionary<int, List<Camera>> CollectObservations()
{
Dictionary<int, List<Camera>> result = new Dictionary<int, List<Camera>>();
foreach (KeyValuePair<int, Agent> idAgent in agents)
{
List<Camera> observations = idAgent.Value.observations;
if (observations.Count < brainParameters.cameraResolutions.Count())
{
throw new UnityAgentsException(string.Format(@"The number of observations does not match for agent {0}:
Was expecting at least {1} observation but received {2}.", idAgent.Value.gameObject.name, brainParameters.cameraResolutions.Count(), observations.Count));
}
result.Add(idAgent.Key, observations);
}
return result;
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal virtual void CreateAddCommand(IDbCommand cmd, object enreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
{
TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());
if (tableInfo.NeedsHistory && tableInfo.IsCreatedByEmpty(enreplacedy))
throw new MissingFieldException("CreatedBy is required when Audit Trail is enabled");
List<string> columns = new List<string>();
if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
else columns.AddRange(tableInfo.DefaultInsertColumns);//Get columns from Enreplacedy attributes loaded in TableInfo
bool isPrimaryKeyEmpty = false;
foreach(ColumnAttribute pkCol in tableInfo.Columns.Where(p=>p.Value.IsPrimaryKey).Select(p=>p.Value))
{
if (pkCol.PrimaryKeyInfo.IsIdenreplacedy && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
{
isPrimaryKeyEmpty = true;
//if idenreplacedy remove keyfield if added in field list
columns.Remove(pkCol.Name);
}
else if (pkCol.Property.PropertyType == typeof(Guid) && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
{
isPrimaryKeyEmpty = true;
//if not idenreplacedy and key not generated, generate before save
tableInfo.SetKeyId(enreplacedy, pkCol, Guid.NewGuid());
}
}
#region append common columns
if (!doNotAppendCommonFields)
{
if (!tableInfo.NoIsActive)
{
if (!columns.Contains(Config.ISACTIVE_COLUMN.Name))
columns.Add(Config.ISACTIVE_COLUMN.Name);
bool isActive = tableInfo.GetIsActive(enreplacedy) ?? true;
//when IsActive is not set then true for insert
cmd.AddInParameter("@" + Config.ISACTIVE_COLUMN.Name, Config.ISACTIVE_COLUMN.ColumnDbType, isActive);
if (tableInfo.NeedsHistory)
audit.AppendDetail(Config.ISACTIVE_COLUMN.Name, isActive, DbType.Boolean, null);
tableInfo.SetIsActive(enreplacedy, isActive); //Set IsActive value
}
if (!tableInfo.NoVersionNo)
{
int versionNo = tableInfo.GetVersionNo(enreplacedy) ?? 1; //set defualt versionno 1 for Insert
if (versionNo == 0) versionNo = 1; //set defualt versionno 1 for Insert even if its zero or null
if (!columns.Contains(Config.VERSIONNO_COLUMN.Name))
columns.Add(Config.VERSIONNO_COLUMN.Name);
cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, versionNo);
tableInfo.SetVersionNo(enreplacedy, versionNo); //Set VersionNo value
}
if (!tableInfo.NoCreatedBy)
{
if (!columns.Contains(Config.CREATEDBY_COLUMN.Name))
columns.Add(Config.CREATEDBY_COLUMN.Name);
cmd.AddInParameter("@" + Config.CREATEDBY_COLUMN.Name, Config.CREATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
}
if (!tableInfo.NoCreatedOn & !columns.Contains(Config.CREATEDON_COLUMN.Name))
{
columns.Add(Config.CREATEDON_COLUMN.Name);
}
if (!tableInfo.NoUpdatedBy)
{
if (!columns.Contains(Config.UPDATEDBY_COLUMN.Name))
columns.Add(Config.UPDATEDBY_COLUMN.Name);
cmd.AddInParameter("@" + Config.UPDATEDBY_COLUMN.Name, Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
}
if (!tableInfo.NoUpdatedOn & !columns.Contains(Config.UPDATEDON_COLUMN.Name))
{
columns.Add(Config.UPDATEDON_COLUMN.Name);
}
}
#endregion
//append @ before each fields to add as parameter
List<string> parameters = columns.Select(c => "@" + c).ToList();
int pIndex = parameters.FindIndex(c => c == "@" + Config.CREATEDON_COLUMN.Name);
if (pIndex >= 0)
{
var createdOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
if (createdOn is string)
{
parameters[pIndex] = (string)createdOn;
}
else
{
cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, createdOn);
}
//parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
}
pIndex = parameters.FindIndex(c => c == "@" + Config.UPDATEDON_COLUMN.Name);
if (pIndex >= 0)
{
var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
if (updatedOn is string)
{
parameters[pIndex] = (string)updatedOn;
}
else
{
cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, updatedOn);
}
//parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
}
StringBuilder cmdText = new StringBuilder();
cmdText.Append($"INSERT INTO {tableInfo.FullName} ({string.Join(",", columns)}) VALUES({string.Join(",", parameters)});");
if (tableInfo.IsKeyIdenreplacedy() && isPrimaryKeyEmpty)
{
//add query to get inserted id
cmdText.Append(LASTINSERTEDROWIDSQL);
}
//remove common columns and parameters already added above
columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name || c == Config.CREATEDBY_COLUMN.Name
|| c == Config.UPDATEDON_COLUMN.Name || c == Config.UPDATEDBY_COLUMN.Name
|| c == Config.VERSIONNO_COLUMN.Name || c == Config.ISACTIVE_COLUMN.Name);
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdText.ToString();
for (int i = 0; i < columns.Count(); i++)
{
tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute
DbType dbType = DbType.Object;
object columnValue = null;
if (columnInfo != null && columnInfo.GetMethod != null)
{
dbType = columnInfo.ColumnDbType;
columnValue = columnInfo.GetAction(enreplacedy);
if (tableInfo.NeedsHistory) audit.AppendDetail(columns[i], columnValue, dbType, null);
}
cmd.AddInParameter("@" + columns[i], dbType, columnValue);
}
}
19
Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
private int GetRecordOffset(BiffRecord record)
{
if (ContainsRecord(record) == false)
{
throw new ArgumentException(string.Format("Could not find record {0}", record));
}
var recordOffset =
_biffRecords.TakeWhile(r => r.Equals(record) == false).Count();
return recordOffset;
}
19
Source : Attributes.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal bool IsKeyIdEmpty(object enreplacedy)
{
if (Columns.Where(p=>p.Value.IsPrimaryKey).Count()==0)
return true;
bool result = false;
foreach (ColumnAttribute c in Columns.Where(p => p.Value.IsPrimaryKey).Select(a=>a.Value))
{
result = IsKeyFieldEmpty(c.GetAction(enreplacedy), c.replacedle);
if (result)
break;
}
return result;
}
19
Source : Attributes.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal bool IsIdenreplacedyKeyIdEmpty(object enreplacedy)
{
if (Columns.Where(p => p.Value.IsPrimaryKey && p.Value.PrimaryKeyInfo.IsIdenreplacedy).Count() == 0)
return true;
ColumnAttribute pkIdenreplacedyCol = Columns.Where(p => p.Value.IsPrimaryKey && p.Value.PrimaryKeyInfo.IsIdenreplacedy).Select(p=>p.Value).FirstOrDefault();
return IsKeyFieldEmpty(pkIdenreplacedyCol.GetAction(enreplacedy), pkIdenreplacedyCol.replacedle);
}
19
Source : EntityCache.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal static TableAttribute PrepareTableAttribute(Type enreplacedy)
{
TableAttribute result = (TableAttribute)enreplacedy.GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault();
if (result == null)
{
result = new TableAttribute
{
Name = enreplacedy.Name, //replaceduming enreplacedy clreplaced name is table name
NeedsHistory = Config.NeedsHistory,
NoCreatedBy = Config.NoCreatedBy,
NoCreatedOn = Config.NoCreatedOn,
NoUpdatedBy = Config.NoUpdatedBy,
NoUpdatedOn = Config.NoUpdatedOn,
NoVersionNo = Config.NoVersionNo,
NoIsActive = Config.NoIsActive
};
}
if (string.IsNullOrEmpty(result.Name)) result.Name = enreplacedy.Name;
//find all properties
var properties = enreplacedy.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
//TODO: check for valid property types to be added in list
if ((property.Name.Equals("keyid", StringComparison.OrdinalIgnoreCase) ||
property.Name.Equals("operation", StringComparison.OrdinalIgnoreCase)))
continue;
//check for ignore property attribute
var ignoreInfo = (IgnoreColumnAttribute)property.GetCustomAttribute(typeof(IgnoreColumnAttribute));
var primaryKey = (PrimaryKeyAttribute)property.GetCustomAttribute(typeof(PrimaryKeyAttribute));
var column = (ColumnAttribute)property.GetCustomAttribute(typeof(ColumnAttribute));
if (column == null) column = new ColumnAttribute();
if (string.IsNullOrEmpty(column.Name)) column.Name = property.Name;
if (property.Name.Equals("CreatedBy", StringComparison.OrdinalIgnoreCase))
column.Name = Config.CreatedByColumnName;
else if (property.Name.Equals("CreatedByName"))
column.Name = Config.CreatedByNameColumnName;
else if (property.Name.Equals("CreatedOn"))
column.Name = Config.CreatedOnColumnName;
else if (property.Name.Equals("UpdatedBy"))
column.Name = Config.UpdatedByColumnName;
else if (property.Name.Equals("UpdatedByName"))
column.Name = Config.UpdatedByNameColumnName;
else if (property.Name.Equals("UpdatedOn"))
column.Name = Config.UpdatedOnColumnName;
else if (property.Name.Equals("VersionNo"))
column.Name = Config.VersionNoColumnName;
else if (property.Name.Equals("IsActive"))
column.Name = Config.IsActiveColumnName;
if (!column.IsColumnDbTypeDefined)
{
if (column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase) ||
column.Name.Equals(Config.UpdatedByColumnName, StringComparison.OrdinalIgnoreCase))
column.ColumnDbType = Config.CreatedUpdatedByColumnType;
else if (property.PropertyType.IsEnum)
column.ColumnDbType = TypeCache.TypeToDbType[property.PropertyType.GetEnumUnderlyingType()];
else if (property.PropertyType.IsValueType)
column.ColumnDbType = TypeCache.TypeToDbType[property.PropertyType];
else
{
TypeCache.TypeToDbType.TryGetValue(property.PropertyType, out DbType columnDbType);
column.ColumnDbType = columnDbType;
}
}
column.SetPropertyInfo(property, enreplacedy);
column.IgnoreInfo = ignoreInfo ?? new IgnoreColumnAttribute(false);
//Primary Key details
if (primaryKey != null)
{
column.PrimaryKeyInfo = primaryKey;
var virtualForeignKeys = (IEnumerable<ForeignKey>)property.GetCustomAttributes(typeof(ForeignKey));
if (virtualForeignKeys != null && virtualForeignKeys.Count() > 0)
{
if (result.VirtualForeignKeys == null) result.VirtualForeignKeys = new List<ForeignKey>();
result.VirtualForeignKeys.AddRange(virtualForeignKeys);
}
}
if (result.NoCreatedBy && (column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase)
|| column.Name.Equals(Config.CreatedByNameColumnName, StringComparison.OrdinalIgnoreCase)))
continue;
else if (result.NoCreatedOn && column.Name.Equals(Config.CreatedOnColumnName, StringComparison.OrdinalIgnoreCase))
continue;
else if (result.NoUpdatedBy && ((column.Name.Equals(Config.UpdatedByColumnName, StringComparison.OrdinalIgnoreCase)
|| column.Name.Equals(Config.UpdatedByNameColumnName, StringComparison.OrdinalIgnoreCase))))
continue;
else if (result.NoUpdatedOn && column.Name.Equals(Config.UpdatedOnColumnName, StringComparison.OrdinalIgnoreCase))
continue;
else if (result.NoIsActive && column.Name.Equals(Config.IsActiveColumnName, StringComparison.OrdinalIgnoreCase))
continue;
else if (result.NoVersionNo && column.Name.Equals(Config.VersionNoColumnName, StringComparison.OrdinalIgnoreCase))
continue;
else
{
if (!column.IgnoreInfo.Insert)
result.DefaultInsertColumns.Add(column.Name);
//isactive,createdon,createdby column shall not be included in default update columns
if (!column.IgnoreInfo.Update
&& !column.Name.Equals(Config.IsActiveColumnName, StringComparison.OrdinalIgnoreCase)
&& !column.Name.Equals(Config.CreatedByColumnName, StringComparison.OrdinalIgnoreCase)
&& !column.Name.Equals(Config.CreatedOnColumnName, StringComparison.OrdinalIgnoreCase))
result.DefaultUpdateColumns.Add(column.Name);
if (!column.IgnoreInfo.Read)
result.DefaultReadColumns.Add(column.Name);
result.Columns[column.Name] = column;
}
}
if(result.Columns.LongCount(p=>p.Value.IsPrimaryKey && p.Value.PrimaryKeyInfo.IsIdenreplacedy) > 1)
{
throw new NotSupportedException("Primary key with multiple Idenreplacedy is not supported on " + result.Name);
}
if (result.Columns.LongCount(p => p.Value.IsPrimaryKey) > 1 && result.NeedsHistory)
{
throw new NotSupportedException($"History for {result.Name} is not supported as it has composite Primary key");
}
return result;
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal virtual bool CreateUpdateCommand(IDbCommand cmd, object enreplacedy, object oldEnreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
{
bool isUpdateNeeded = false;
TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());
if (!tableInfo.NoUpdatedBy && tableInfo.IsUpdatedByEmpty(enreplacedy))
throw new MissingFieldException("Updated By is required");
List<string> columns = new List<string>();
if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
else columns.AddRange(tableInfo.DefaultUpdateColumns);//Get columns from Enreplacedy attributes loaded in TableInfo
StringBuilder cmdText = new StringBuilder();
cmdText.Append($"UPDATE {tableInfo.FullName} SET ");
//add default columns if doesn't exists
if (!doNotAppendCommonFields)
{
if (!tableInfo.NoVersionNo && !columns.Contains(Config.VERSIONNO_COLUMN.Name))
columns.Add(Config.VERSIONNO_COLUMN.Name);
if (!tableInfo.NoUpdatedBy && !columns.Contains(Config.UPDATEDBY_COLUMN.Name))
columns.Add(Config.UPDATEDBY_COLUMN.Name);
if (!tableInfo.NoUpdatedOn && !columns.Contains(Config.UPDATEDON_COLUMN.Name))
columns.Add(Config.UPDATEDON_COLUMN.Name);
}
//remove primarykey, createdon and createdby columns if exists
columns.RemoveAll(c => tableInfo.PkColumnList.Select(p=>p.Name).Contains(c));
columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name ||
c == Config.CREATEDBY_COLUMN.Name);
for (int i = 0; i < columns.Count(); i++)
{
if (columns[i].Equals(Config.VERSIONNO_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
cmdText.Append($"{columns[i]} = {columns[i]}+1");
cmdText.Append(",");
}
else if (columns[i].Equals(Config.UPDATEDBY_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmdText.Append(",");
cmd.AddInParameter("@" + columns[i], Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetUpdatedBy(enreplacedy));
}
else if (columns[i].Equals(Config.UPDATEDON_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
if (updatedOn is string)
{
cmdText.Append($"{columns[i]} = {CURRENTDATETIMESQL}");
}
else
{
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmd.AddInParameter("@" + columns[i], Config.UPDATEDON_COLUMN.ColumnDbType, updatedOn);
}
cmdText.Append(",");
}
else
{
bool includeInUpdate = true;
tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute
DbType dbType = DbType.Object;
object columnValue = null;
if (columnInfo != null && columnInfo.GetMethod != null)
{
dbType = columnInfo.ColumnDbType;
columnValue = columnInfo.GetAction(enreplacedy);
includeInUpdate = oldEnreplacedy == null; //include in update when oldEnreplacedy not available
//compare with old object to check whether update is needed or not
object oldColumnValue = null;
if (oldEnreplacedy != null)
{
oldColumnValue = columnInfo.GetAction(oldEnreplacedy);
if (oldColumnValue != null && columnValue != null)
{
if (!oldColumnValue.Equals(columnValue)) //add to history only if property is modified
{
includeInUpdate = true;
}
}
else if (oldColumnValue == null && columnValue != null)
{
includeInUpdate = true;
}
else if (oldColumnValue != null)
{
includeInUpdate = true;
}
}
if (tableInfo.NeedsHistory && includeInUpdate) audit.AppendDetail(columns[i], columnValue, dbType, oldColumnValue);
}
if (includeInUpdate)
{
isUpdateNeeded = true;
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmdText.Append(",");
cmd.AddInParameter("@" + columns[i], dbType, columnValue);
}
}
}
cmdText.RemoveLastComma(); //Remove last comma if exists
cmdText.Append(" WHERE ");
if (tableInfo.PkColumnList.Count > 1)
{
int index = 0;
foreach (ColumnAttribute pkCol in tableInfo.PkColumnList)
{
cmdText.Append($" {(index > 0 ? " AND " : "")} {pkCol.Name}=@{pkCol.Name}");
cmd.AddInParameter("@" + pkCol.Name, pkCol.ColumnDbType, tableInfo.GetKeyId(enreplacedy, pkCol));
index++;
}
}
else
{
cmdText.Append($" {tableInfo.PkColumn.Name}=@{tableInfo.PkColumn.Name}");
cmd.AddInParameter("@" + tableInfo.PkColumn.Name, tableInfo.PkColumn.ColumnDbType, tableInfo.GetKeyId(enreplacedy));
}
if (Config.DbConcurrencyCheck && !tableInfo.NoVersionNo)
{
cmdText.Append($" AND {Config.VERSIONNO_COLUMN.Name}=@{Config.VERSIONNO_COLUMN.Name}");
cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, tableInfo.GetVersionNo(enreplacedy));
}
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdText.ToString();
return isUpdateNeeded;
}
19
Source : Remute.cs
with MIT License
from ababik
with MIT License
from ababik
private PropertyInfo FindProperty(Type type, ParameterInfo parameter, PropertyInfo[] properties)
{
if (ActivationConfiguration.Settings.TryGetValue(type, out var setting))
{
if (setting.Parameters.TryGetValue(parameter, out var property))
{
return property;
}
}
properties = properties.Where(x => string.Equals(x.Name, parameter.Name, StringComparison.OrdinalIgnoreCase)).ToArray();
if (properties.Count() != 1)
{
throw new Exception($"Unable to find appropriate property to use as a constructor parameter '{parameter.Name}'. Type '{type.Name}'. Consider to use {nameof(ActivationConfiguration)} parameter.");
}
return properties.Single();
}
19
Source : LogManagerTests.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
[Test]
public void should_return_special_log_event_when_no_more_log_event_are_available()
{
var log = LogManager.GetLogger(typeof(LogManagerTests));
var actualLogEvents = new List<ILogEvent>();
for (var i = 0; i < 10; i++)
{
actualLogEvents.Add(log.Debug());
}
var unavailableEvent = log.Debug();
Check.That(actualLogEvents.OfType<LogEvent>().Count()).Equals(actualLogEvents.Count);
Check.That(unavailableEvent).IsInstanceOf<ForwardingLogEvent>();
var signal = _testAppender.SetMessageCountTarget(actualLogEvents.Count);
for (var i = 0; i < actualLogEvents.Count; i++)
{
var actualLogEvent = actualLogEvents[i];
actualLogEvent.Append(i).Log();
}
signal.Wait(TimeSpan.FromMilliseconds(100));
Check.That(log.Debug()).IsInstanceOf<LogEvent>();
}
19
Source : MathUtilities.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static Vector3 NearestPointToLinesRANSAC(List<Ray> rays, int ransac_iterations, float ransac_threshold, out int numActualInliers)
{
// start with something, just in case no inliers - this works for case of 1 or 2 rays
Vector3 nearestPoint = NearestPointToLines(rays[0], rays[rays.Count - 1]);
numActualInliers = 0;
if (rays.Count > 2)
{
for (int it = 0; it < ransac_iterations; it++)
{
Vector3 testPoint = NearestPointToLines(rays[Random.Range(0, rays.Count)], rays[Random.Range(0, rays.Count)]);
// count inliers
int numInliersForIteration = 0;
for (int ind = 0; ind < rays.Count; ++ind)
{
if (DistanceOfPointToLine(rays[ind], testPoint) < ransac_threshold)
++numInliersForIteration;
}
// remember best
if (numInliersForIteration > numActualInliers)
{
numActualInliers = numInliersForIteration;
nearestPoint = testPoint;
}
}
}
// now find and count actual inliers and do least-squares to find best fit
IEnumerable<Ray> inlierList = rays.Where(r => DistanceOfPointToLine(r, nearestPoint) < ransac_threshold);
numActualInliers = inlierList.Count();
if (numActualInliers >= 2)
{
nearestPoint = NearestPointToLinesLeastSquares(inlierList);
}
return nearestPoint;
}
19
Source : SurfaceMeshWithPaletteProvider.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public Color? OverrideCellColor(IRenderableSeries3D series, int xIndex, int zIndex)
{
if (zIndex == 0 || xIndex == 0 ||
zIndex == 47 || xIndex == 47)
{
return _colors[_random.Next(1, _colors.Count())];
}
else if ((zIndex >= 20 && zIndex <= 26) || (xIndex >= 20 && xIndex <= 26))
{
return (Color?)Colors.Transparent;
}
return _colors[_random.Next(1, _colors.Count())];
}
19
Source : PolarChartViewModelFactory.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static IXyzDataSeries<double, double, double> GetXyzDataSeries(IEnumerable<double> data)
{
var dataSeries = new XyzDataSeries<double, double, double>();
dataSeries.Append(data, data, Enumerable.Repeat(30d, data.Count()));
return dataSeries;
}
19
Source : FileCache.cs
with Apache License 2.0
from acarteas
with Apache License 2.0
from acarteas
public override long GetCount(string regionName = null)
{
if (regionName == null)
{
regionName = "";
}
string path = Path.Combine(CacheDir, _cacheSubFolder, regionName);
if (Directory.Exists(path))
return Directory.GetFiles(path).Count();
else
return 0;
}
19
Source : LazyTreeNodeExtensions.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public int Count() => Flatten(_seed).Count();
19
Source : CommandParameterHelpers.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
{
string parameterBlob = "";
if (rawIncluded)
{
parameterBlob = aceParsedParameters.First();
}
else
{
parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
}
int commaCount = parameterBlob.Count(x => x == ',');
List<ACECommandParameter> acps = parameters.ToList();
for (int i = acps.Count - 1; i > -1; i--)
{
ACECommandParameter acp = acps[i];
acp.ParameterNo = i + 1;
if (parameterBlob.Length > 0)
{
try
{
switch (acp.Type)
{
case ACECommandParameterType.PositiveLong:
Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match4.Success)
{
if (!long.TryParse(match4.Groups[1].Value, out long val))
{
return false;
}
if (val <= 0)
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
}
break;
case ACECommandParameterType.Long:
Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match3.Success)
{
if (!long.TryParse(match3.Groups[1].Value, out long val))
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
break;
case ACECommandParameterType.ULong:
Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match2.Success)
{
if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
break;
case ACECommandParameterType.Location:
Position position = null;
Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
if (match.Success)
{
string ns = match.Groups[1].Value;
string ew = match.Groups[2].Value;
if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
{
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMessage);
}
return false;
}
else
{
acp.Value = position;
acp.Defaulted = false;
int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
}
}
break;
case ACECommandParameterType.OnlinePlayerName:
if (i != 0)
{
throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
}
parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
if (targetPlayer == null)
{
string errorMsg = $"Unable to find player {parameterBlob}";
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMsg);
}
return false;
}
else
{
acp.Value = targetPlayer;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.OnlinePlayerNameOrIid:
if (i != 0)
{
throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
}
if (!parameterBlob.Contains(' '))
{
if (uint.TryParse(parameterBlob, out uint iid))
{
Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
if (targetPlayer2 == null)
{
string logMsg = $"Unable to find player with iid {iid}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer2;
acp.Defaulted = false;
break;
}
}
}
Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
if (targetPlayer3 == null)
{
string logMsg = $"Unable to find player {parameterBlob}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer3;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.OnlinePlayerIid:
Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
if (matcha5.Success)
{
string strIid = "";
if (matcha5.Groups[2].Success)
{
strIid = matcha5.Groups[2].Value;
}
else if (matcha5.Groups[1].Success)
{
strIid = matcha5.Groups[1].Value;
}
try
{
uint iid = 0;
if (strIid.StartsWith("0x"))
{
iid = Convert.ToUInt32(strIid, 16);
}
else
{
iid = uint.Parse(strIid);
}
Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
if (targetPlayer2 == null)
{
string logMsg = $"Unable to find player with iid {strIid}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer2;
acp.Defaulted = false;
parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
}
catch (Exception)
{
string errorMsg = $"Unable to parse {strIid} into a player iid";
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMsg);
}
return false;
}
}
break;
case ACECommandParameterType.PlayerName:
if (i != 0)
{
throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
}
parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
if (string.IsNullOrWhiteSpace(parameterBlob))
{
break;
}
else
{
acp.Value = parameterBlob;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.Uri:
Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
if (match5.Success)
{
string strUri = match5.Groups[1].Value;
try
{
Uri url = new Uri(strUri);
acp.Value = url;
acp.Defaulted = false;
parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.DoubleQuoteEnclosedText:
Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
if (match6.Success)
{
string txt = match6.Groups[1].Value;
try
{
acp.Value = txt.Trim('"');
acp.Defaulted = false;
parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.CommaPrefixedText:
if (i == 0)
{
throw new Exception("this parameter type is not appropriate as the first parameter");
}
if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
{
break;
}
Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
if (match7.Success)
{
string txt = match7.Groups[1].Value;
try
{
acp.Value = txt.TrimStart(new char[] { ' ', ',' });
acp.Defaulted = false;
parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.SimpleWord:
Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
if (match8.Success)
{
string txt = match8.Groups[1].Value;
try
{
acp.Value = txt.TrimStart(' ');
acp.Defaulted = false;
parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.Enum:
if (acp.PossibleValues == null)
{
throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
}
if (!acp.PossibleValues.IsEnum)
{
throw new Exception("PossibleValues must be an enum type");
}
Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
if (match9.Success)
{
string txt = match9.Groups[1].Value;
try
{
txt = txt.Trim(new char[] { ' ', ',' });
Array etvs = Enum.GetValues(acp.PossibleValues);
foreach (object etv in etvs)
{
if (etv.ToString().ToLower() == txt.ToLower())
{
acp.Value = etv;
acp.Defaulted = false;
parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
break;
}
}
}
catch (Exception)
{
return false;
}
}
break;
}
}
catch
{
return false;
}
}
if (acp.Defaulted)
{
acp.Value = acp.DefaultValue;
}
if (acp.Required && acp.Defaulted)
{
if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
{
if (session != null)
{
ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(acp.ErrorMessage);
}
}
return false;
}
}
return true;
}
19
Source : HouseManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void QueryMultiHouse()
{
var slumlordBiotas = DatabaseManager.Shard.BaseDatabase.GetBiotasByType(WeenieType.SlumLord);
var playerHouses = new Dictionary<IPlayer, List<Biota>>();
var accountHouses = new Dictionary<string, List<Biota>>();
foreach (var slumlord in slumlordBiotas)
{
var biotaOwner = slumlord.BiotaPropertiesIID.FirstOrDefault(i => i.Type == (ushort)PropertyInstanceId.HouseOwner);
if (biotaOwner == null)
{
// this is fine. this is just a house that was purchased, and then later abandoned
//Console.WriteLine($"HouseManager.QueryMultiHouse(): couldn't find owner for house {slumlord.Id:X8}");
continue;
}
var owner = PlayerManager.FindByGuid(biotaOwner.Value);
if (owner == null)
{
Console.WriteLine($"HouseManager.QueryMultiHouse(): couldn't find owner {biotaOwner.Value:X8}");
continue;
}
if (!playerHouses.TryGetValue(owner, out var houses))
{
houses = new List<Biota>();
playerHouses.Add(owner, houses);
}
houses.Add(slumlord);
var accountName = owner.Account != null ? owner.Account.AccountName : "NULL";
if (!accountHouses.TryGetValue(accountName, out var aHouses))
{
aHouses = new List<Biota>();
accountHouses.Add(accountName, aHouses);
}
aHouses.Add(slumlord);
}
if (PropertyManager.GetBool("house_per_char").Item)
{
var results = playerHouses.Where(i => i.Value.Count() > 1).OrderByDescending(i => i.Value.Count());
if (results.Count() > 0)
Console.WriteLine("Multi-house owners:");
foreach (var playerHouse in results)
{
Console.WriteLine($"{playerHouse.Key.Name}: {playerHouse.Value.Count}");
for (var i = 0; i < playerHouse.Value.Count; i++)
Console.WriteLine($"{i + 1}. {GetCoords(playerHouse.Value[i])}");
}
}
else
{
var results = accountHouses.Where(i => i.Value.Count() > 1).OrderByDescending(i => i.Value.Count());
if (results.Count() > 0)
Console.WriteLine("Multi-house owners:");
foreach (var accountHouse in results)
{
Console.WriteLine($"{accountHouse.Key}: {accountHouse.Value.Count}");
for (var i = 0; i < accountHouse.Value.Count; i++)
Console.WriteLine($"{i + 1}. {GetCoords(accountHouse.Value[i])}");
}
}
}
19
Source : QueueExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static void EnqueueFirst<T>(this Queue<T> q, IEnumerable<T> items)
{
if (items == null || !items.Any()) return;
foreach (var item in items)
q.Enqueue(item);
for (var i = items.Count(); i < q.Count; i++)
q.Enqueue(q.Dequeue());
}
19
Source : Player_Trade.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public Player GetKnownTradeObj(ObjectGuid itemGuid)
{
if (KnownTradeObjs.Count() == 0)
return null;
PruneKnownTradeObjs();
foreach (var knownTradeObj in KnownTradeObjs)
{
if (knownTradeObj.Value.Contains(itemGuid))
{
var playerGuid = knownTradeObj.Key;
var player = ObjMaint.GetKnownObject(playerGuid.Full)?.WeenieObj?.WorldObject as Player;
if (player != null && player.Location != null && Location.DistanceTo(player.Location) <= LocalBroadcastRange)
return player;
else
return null;
}
}
return null;
}
See More Examples