void Dispose(bool _) { if (!disposed) { raw?.ForEach(b => b.Value?.Dispose()); txtFont?.Dispose(); txtBrush?.Dispose(); disposed = true; } }
public static void Unload() { _rotatingRoleColors.ForEach(x => x.Value?.Change(Timeout.Infinite, Timeout.Infinite)); _rotatingRoleColors.Clear(); }
//private //Runs in O(N log(N)) for all players private void UpdateRankings(IEnumerable <Player> players) { try { Dictionary <int, float> oldRatings = new Dictionary <int, float>(); //check for ladder elo updates using (var db = new ZkDataContext()) { var battleIDs = pendingDebriefings.Keys.ToList(); var lastBattlePlayers = db.SpringBattlePlayers.Where(p => battleIDs.Contains(p.SpringBattleID) && !p.IsSpectator).Include(x => x.Account).DistinctBy(x => x.AccountID).ToList(); oldRatings = lastBattlePlayers.ToDictionary(p => (p.AccountID), p => GetPlayerRating(p.AccountID).LadderElo); lastBattlePlayers.Where(p => !playerRatings.ContainsKey((p.AccountID))).ForEach(p => playerRatings[(p.AccountID)] = new PlayerRating(DefaultRating)); lastBattlePlayers.ForEach(p => playerRatings[(p.AccountID)].LadderElo = Ranks.UpdateLadderRating(p.Account, category, getPlayerById((p.AccountID)).avgElo + RatingOffset, p.IsInVictoryTeam, !p.IsInVictoryTeam, db)); db.SaveChanges(); } //update ladders int currentDay = RatingSystems.ConvertDateToDays(DateTime.UtcNow); int playerCount = 0; using (var db = new ZkDataContext()) { foreach (var p in players) { if (p.days.Count == 0) { Trace.TraceError("WHR " + category + " has invalid player " + p.id + " with no days(games)"); continue; } float elo = p.days.Last().GetElo() + RatingOffset; float lastNaturalRatingVar = p.days.Last().naturalRatingVariance; var lastDay = p.days.Last(); float ladderElo; if (playerRatings.ContainsKey(p.id)) { ladderElo = playerRatings[p.id].LadderElo; } else { ladderElo = (float?)db.AccountRatings.Where(x => x.AccountID == p.id && x.RatingCategory == category).FirstOrDefault()?.LadderElo ?? DefaultRating.LadderElo; } playerRatings[p.id] = new PlayerRating(int.MaxValue, 1, elo, lastNaturalRatingVar, GlobalConst.NaturalRatingVariancePerDay(lastDay.totalWeight), lastDay.day, currentDay, ladderElo, !float.IsNaN(p.avgElo)); float rating = -playerRatings[p.id].LadderElo; if (playerKeys.ContainsKey(p.id)) { sortedPlayers.Remove(playerKeys[p.id]); } while (sortedPlayers.ContainsKey(rating)) { rating += 0.01f; } playerKeys[p.id] = rating; sortedPlayers[rating] = p.id; if (playerRatings[p.id].Ranked) { playerCount++; } } } this.activePlayers = playerCount; int rank = 0; List <int> newTopPlayers = new List <int>(); int matched = 0; List <float> newPercentileBrackets = new List <float>(); newPercentileBrackets.Add(playerRatings[sortedPlayers.First().Value].LadderElo); float percentile; float[] percentilesRev = Ranks.Percentiles.Reverse().ToArray(); foreach (var pair in sortedPlayers) { if (playerRatings[pair.Value].Ranked) { newTopPlayers.Add(pair.Value); if (rank == matched && rank < topPlayers.Count && topPlayers[rank] == pair.Value) { matched++; } rank++; percentile = (float)rank / activePlayers; if (newPercentileBrackets.Count <= Ranks.Percentiles.Length && percentile > percentilesRev[newPercentileBrackets.Count - 1]) { newPercentileBrackets.Add(playerRatings[pair.Value].LadderElo); } playerRatings[pair.Value].ApplyLadderUpdate(rank, percentile, currentDay, true); } else if (playerRatings[pair.Value].Rank < int.MaxValue) { playerRatings[pair.Value].ApplyLadderUpdate(int.MaxValue, 1, currentDay, false); } } if (rank != playerCount) { Trace.TraceWarning("WHR has " + playerCount + " active players, but " + rank + " sorted active players"); } while (newPercentileBrackets.Count < Ranks.Percentiles.Length + 1) { newPercentileBrackets.Add(playerRatings[sortedPlayers.Last().Value].LadderElo); } PercentileBrackets = newPercentileBrackets.Select(x => x).Reverse().ToArray(); topPlayers = newTopPlayers; laddersCache = new List <Account>(); Trace.TraceInformation("WHR " + category + " Ladders updated with " + topPlayers.Count + "/" + this.players.Count + " entries. Brackets are now: " + string.Join(", ", PercentileBrackets)); var playerIds = players.Select(x => x.id).ToList(); if (playerIds.Count() < 100) { SaveToDB(playerIds); } else { SaveToDB(); } //check for rank updates if (pendingDebriefings.Any()) { List <int> playersWithRatingChange = new List <int>(); Dictionary <int, int> oldRanks = new Dictionary <int, int>(); Dictionary <int, Account> updatedRanks = new Dictionary <int, Account>(); Dictionary <int, Account> involvedAccounts = new Dictionary <int, Account>(); Trace.TraceInformation("WHR Filling in Debriefings for Battles: " + pendingDebriefings.Keys.Select(x => "B" + x).StringJoin()); using (var db = new ZkDataContext()) { var battleIDs = pendingDebriefings.Keys.ToList(); var lastBattlePlayers = db.SpringBattlePlayers.Where(p => battleIDs.Contains(p.SpringBattleID) && !p.IsSpectator).Include(x => x.Account).ToList(); involvedAccounts = lastBattlePlayers.ToDictionary(p => p.AccountID, p => p.Account); Trace.TraceInformation("WHR Debriefing players: " + involvedAccounts.Values.Select(x => x.Name).StringJoin()); oldRanks = lastBattlePlayers.ToDictionary(p => p.AccountID, p => p.Account.Rank); updatedRanks = lastBattlePlayers.Where(p => Ranks.UpdateRank(p.Account, p.IsInVictoryTeam, !p.IsInVictoryTeam, db)).Select(x => x.Account).ToDictionary(p => p.AccountID, p => p); updatedRanks.Values.ForEach(p => db.Entry(p).State = EntityState.Modified); playersWithRatingChange = lastBattlePlayers.Select(x => x.AccountID).ToList(); lastBattlePlayers.Where(p => playerOldRatings.ContainsKey((p.AccountID)) && !p.EloChange.HasValue).ForEach(p => { //p.EloChange = playerRatings[(p.AccountID)].RealElo - playerOldRatings[(p.AccountID)].RealElo; p.EloChange = playerRatings[(p.AccountID)].LadderElo - oldRatings[(p.AccountID)]; }); db.SpringBattlePlayers.Where(p => battleIDs.Contains(p.SpringBattleID) && !p.IsSpectator).ToList().ForEach(x => playerOldRatings[(x.AccountID)] = playerRatings[(x.AccountID)]); db.SaveChanges(); } //Publish new results only after saving new stats to db. pendingDebriefings.ForEach(pair => { pair.Value.partialDebriefing.DebriefingUsers.Values.ForEach(user => { try { user.EloChange = playerRatings[(user.AccountID)].LadderElo - oldRatings[(user.AccountID)]; user.IsRankup = updatedRanks.ContainsKey(user.AccountID) && oldRanks[user.AccountID] < updatedRanks[user.AccountID].Rank; user.IsRankdown = updatedRanks.ContainsKey(user.AccountID) && oldRanks[user.AccountID] > updatedRanks[user.AccountID].Rank; var prog = Ranks.GetRankProgress(involvedAccounts[user.AccountID], this); if (prog == null) { Trace.TraceWarning("User " + user.AccountID + " is wrongfully unranked"); } user.NextRankElo = prog.RankCeilElo; user.PrevRankElo = prog.RankFloorElo; user.NewElo = prog.CurrentElo; } catch (Exception ex) { Trace.TraceError("Unable to complete debriefing for user " + user.AccountID + ": " + ex); } }); pair.Value.partialDebriefing.RatingCategory = category.ToString(); pair.Value.debriefingConsumer.Invoke(pair.Value.partialDebriefing); }); RatingsUpdated(this, new RatingUpdate() { affectedPlayers = playersWithRatingChange }); pendingDebriefings.Clear(); } //check for topX updates GetTopPlayers(GlobalConst.LadderSize); foreach (var listener in topPlayersUpdateListeners) { if (matched < listener.Value) { listener.Key.TopPlayersUpdated(GetTopPlayers(listener.Value)); } } } catch (Exception ex) { string dbg = "WHR " + category + ": Failed to update rankings " + ex + "\nPlayers: "; foreach (var p in players) { dbg += p.id + " (" + p.days.Count + " days), "; } Trace.TraceError(dbg); } }
public void ProcessBattle(SpringBattle battle) { ICollection <int> winners = battle.SpringBattlePlayers .Where(p => p.IsInVictoryTeam && !p.IsSpectator) .Select(p => (p.AccountID)) .Distinct() .ToList(); ICollection <ICollection <int> > losers = battle.SpringBattlePlayers .Where(p => !p.IsInVictoryTeam && !p.IsSpectator) .GroupBy(p => p.AllyNumber) .Select(t => (ICollection <int>)t.Select(p => p.AccountID).Distinct().ToList()) .ToList(); int date = RatingSystems.ConvertDateToDays(battle.StartTime); if (RatingSystems.Initialized) { if (losers.Any(t => winners.Intersect(t).Any())) { Trace.TraceWarning("WHR B" + battle.SpringBattleID + " has winner loser intersection"); } if (ProcessedBattles.Contains(battle.SpringBattleID)) { Trace.TraceWarning("WHR B" + battle.SpringBattleID + " has already been processed"); } if (winners.Count == 0) { Trace.TraceWarning("WHR B" + battle.SpringBattleID + " has no winner"); } if (losers.Count == 0) { Trace.TraceWarning("WHR B" + battle.SpringBattleID + " has no loser"); } } if (!losers.Any(t => winners.Intersect(t).Any()) && !ProcessedBattles.Contains(battle.SpringBattleID) && winners.Count > 0 && losers.Count > 0) { battlesRegistered++; ProcessedBattles.Add(battle.SpringBattleID); if (date > RatingSystems.ConvertDateToDays(DateTime.UtcNow)) { Trace.TraceWarning("WHR " + category + ": Tried to register battle " + battle.SpringBattleID + " which is from the future " + (date) + " > " + RatingSystems.ConvertDateToDays(DateTime.UtcNow)); } else { CreateGame(winners, losers, date, battle.SpringBattleID); futureDebriefings.ForEach(u => pendingDebriefings.TryAdd(u.Key, u.Value)); futureDebriefings.Clear(); if (RatingSystems.Initialized) { Trace.TraceInformation(battlesRegistered + " battles registered for WHR " + category + ", latest Battle: " + battle.SpringBattleID); UpdateRatings(); } } } else { PendingDebriefing debriefing; futureDebriefings.TryGetValue(battle.SpringBattleID, out debriefing); if (debriefing == null) { pendingDebriefings.TryGetValue(battle.SpringBattleID, out debriefing); } if (debriefing != null) { Trace.TraceWarning("Battle " + battle.SpringBattleID + " was processed before attaching pending report"); debriefing.debriefingConsumer.Invoke(debriefing.partialDebriefing); } } }
/// <inheritdoc cref="IDisposable.Dispose" /> public void Dispose() { _connections.ForEach(c => c.Value?.Dispose()); _connections.Clear(); }
private void monitorConnections() { do { try { var forRemovalConnectionIds = new List <string>(); int currentRunning = 0; int currentWaitingForActivation = 0; _connections.ForEach(c => { if (c.Value.task == null) { Log("Found Connection without task (Connection.status: " + c.Value.status.ToString() + "). Ignoring"); // forRemovalConnectionIds.Add(connectionId); // Dukket opp ved bytte til 64 bit kanskje? } else { switch (c.Value.task.Status) { case TaskStatus.Running: currentRunning++; break; // Do nothing with this case TaskStatus.WaitingForActivation: // Får jeg bare denne på Windows Server, ikke Windows Professional? currentWaitingForActivation++; break; // Gjør ingenting med denne case TaskStatus.Canceled: case TaskStatus.Faulted: // Kan for eksempel skyldes at klienten har sendt tom melding og at vi har terminert forbindelsen? Men kommer den virkelig da i "Faulted"? Log("Found task with status " + c.Value.task.Status.ToString() + " (" + c.Value.status + ")"); forRemovalConnectionIds.Add(c.Key); // Det har skjedd noe fundamental galt nå men vi vet ikke nøyaktig hva. Sjekk koden i HandleConnectionAsync break; case TaskStatus.RanToCompletion: // Log("Found task with status " + connectionId.task.status.ToString() + " (" + connectionId.status + ")"); forRemovalConnectionIds.Add(c.Key); // Denne logger vi ikke break; default: Log("Unknown TaskStatus (" + c.Value.task.Status.ToString() + ") (" + c.Value.task.Status + "), will remove from Collection (this message will not occur again for this task)"); Increase("Connections_UnknownTaskStatus_Count_" + c.Value.task.Status.ToString()); // Bemerk at "gamle" data i databasen vil bli liggende når Listener restartes fordi vi nullstiller ikke tellingen forRemovalConnectionIds.Add(c.Key); break; } } // Also remove the connections which are dead //if (c.Value.isDead) forRemovalConnectionIds.Add(c.Key); }); _statistics[BPAPIData.DeviceProperty.Connection_Count.ToString()] = _connections.Count; _statistics[BPAPIData.DeviceProperty.Connection_CurrentWaitingForActivation.ToString()] = currentWaitingForActivation; _statistics[BPAPIData.DeviceProperty.Connection_CurrentRunning.ToString()] = currentRunning; if (forRemovalConnectionIds.Count > 0) { Log("_connections.Count: " + _connections.Count + ", forRemovalConnectionIds.Count: " + forRemovalConnectionIds.Count); } forRemovalConnectionIds.ForEach(connectionId => { Connection removableConnection; if (_connections.TryRemove(connectionId, out removableConnection)) { Increase("Connections_Count_" + removableConnection.task.Status.ToString()); if (removableConnection.task.Exception != null) // Viktig at sjekker nå, hvis ikke blir disse helt usynlige og aldri logget. { Increase("Connections_Count_Exceptions_" + removableConnection.task.Status.ToString()); Log("Found Exception " + removableConnection.task.Exception.GetType().ToString() + " for task with status " + removableConnection.task.Status.ToString()); if (removableConnection.task.Exception is System.AggregateException) { var e = ((System.AggregateException)removableConnection.task.Exception); if (e.InnerExceptions.Count > 0) { Log(removableConnection.task.Exception.GetType().ToString() + ": First inner exception is of type " + e.InnerExceptions[0].GetType().ToString()); } } HandleException(removableConnection.task.Exception); } } }); if (forRemovalConnectionIds.Count > 0) { Log("_connections.Count: " + _connections.Count); } } catch (Exception ex) { Log(ex.GetType().ToString() + " in MonitorConnections"); if (ex.Message.Contains("Collection was modified; enumeration operation may not execute")) { Log("Ignoring because may happen now and then, but without any real consequence: '" + ex.Message + "'"); } else { HandleException(ex); } } finally { System.Threading.Thread.Sleep(5000); } } while (true); }
protected static void OnNodeIdAvailable(IReferenceByGuid referenceByGuid, Guid guid) { EnsureDisposedHandlersRemoved(); NodeIdHandlers.ForEach(x => x.Value.Invoke(referenceByGuid, guid)); }
/// <summary> /// Abort all open transactions /// </summary> public void Dispose() { _transactions.ForEach((x, i) => i.Value.Abort()); }
private void ClearDbs() { _dbs.ForEach(x => x.Value.Dispose()); _dbs.Clear(); }
public void Dispose() { // Dispose individual loggers _table.ForEach(x => x.Value.Dispose()); }
private void UpdateFormatting() { bool updateVariables = false; foreach (var entry in _overlayEntries) { if (entry.FormatChanged) { updateVariables = true; // group name format var basicGroupFormat = entry.GroupSeparators == 0 ? "{0}" : Enumerable.Repeat("\n", entry.GroupSeparators).Aggregate((i, j) => i + j) + "{0}"; var groupNameFormatStringBuilder = new StringBuilder(); groupNameFormatStringBuilder.Append("<S="); groupNameFormatStringBuilder.Append(entry.GroupFontSize.ToString()); AppendColorFormat(groupNameFormatStringBuilder, entry.GroupColor); groupNameFormatStringBuilder.Append(basicGroupFormat); groupNameFormatStringBuilder.Append(" <C><S>"); entry.GroupNameFormat = groupNameFormatStringBuilder.ToString(); if (entry.ValueUnitFormat != null && entry.ValueAlignmentAndDigits != null) { var valueFormatStringBuilder = new StringBuilder(); valueFormatStringBuilder.Append("<S="); valueFormatStringBuilder.Append(entry.ValueFontSize.ToString()); AppendColorFormat(valueFormatStringBuilder, entry.Color); valueFormatStringBuilder.Append(entry.ValueAlignmentAndDigits); valueFormatStringBuilder.Append("<C><S>"); valueFormatStringBuilder.Append("<S="); valueFormatStringBuilder.Append((entry.ValueFontSize / 2).ToString()); AppendColorFormat(valueFormatStringBuilder, entry.Color); valueFormatStringBuilder.Append(entry.ValueUnitFormat); valueFormatStringBuilder.Append("<C><S>"); entry.ValueFormat = valueFormatStringBuilder.ToString(); } else { var valueFormatStringBuilder = new StringBuilder(); valueFormatStringBuilder.Append("<S="); valueFormatStringBuilder.Append(entry.ValueFontSize.ToString()); AppendColorFormat(valueFormatStringBuilder, entry.Color); valueFormatStringBuilder.Append("{0}<C><S>"); entry.ValueFormat = valueFormatStringBuilder.ToString(); } // reset format changed and last limit state entry.FormatChanged = false; entry.LastLimitState = LimitState.Undefined; } // check value limits if (entry.ShowOnOverlay) { if (!(entry.LowerLimitValue == string.Empty && entry.UpperLimitValue == string.Empty)) { var currentColor = string.Empty; bool upperLimit = false; bool lowerLimit = false; LimitState limitState = LimitState.Undefined; if (entry.Value == null) { continue; } if (entry.UpperLimitValue != string.Empty) { if (!double.TryParse(entry.Value.ToString(), out double currentConvertedValue)) { continue; } if (!double.TryParse(entry.UpperLimitValue, NumberStyles.Float, CultureInfo.InvariantCulture, out double convertedUpperValue)) { continue; } if (currentConvertedValue >= convertedUpperValue) { currentColor = entry.UpperLimitColor; upperLimit = true; limitState = LimitState.Upper; } } if (entry.LowerLimitValue != string.Empty) { if (!upperLimit) { if (!double.TryParse(entry.Value.ToString(), out double currentConvertedValue)) { continue; } if (!double.TryParse(entry.LowerLimitValue, NumberStyles.Float, CultureInfo.InvariantCulture, out double convertedLowerValue)) { continue; } if (currentConvertedValue <= convertedLowerValue) { currentColor = entry.LowerLimitColor; lowerLimit = true; limitState = LimitState.Lower; } } } if (!upperLimit && !lowerLimit) { currentColor = entry.Color; limitState = LimitState.None; } if (limitState != entry.LastLimitState) { if (entry.ValueUnitFormat != null && entry.ValueAlignmentAndDigits != null) { updateVariables = true; var valueFormatStringBuilder = new StringBuilder(); valueFormatStringBuilder.Append("<S="); valueFormatStringBuilder.Append(entry.ValueFontSize.ToString()); AppendColorFormat(valueFormatStringBuilder, currentColor); valueFormatStringBuilder.Append(entry.ValueAlignmentAndDigits); valueFormatStringBuilder.Append("<C><S>"); valueFormatStringBuilder.Append("<S="); valueFormatStringBuilder.Append((entry.ValueFontSize / 2).ToString()); AppendColorFormat(valueFormatStringBuilder, currentColor); valueFormatStringBuilder.Append(entry.ValueUnitFormat); valueFormatStringBuilder.Append("<C><S>"); entry.ValueFormat = valueFormatStringBuilder.ToString(); } else { updateVariables = true; var valueFormatStringBuilder = new StringBuilder(); valueFormatStringBuilder.Append("<S="); valueFormatStringBuilder.Append(entry.ValueFontSize.ToString()); AppendColorFormat(valueFormatStringBuilder, currentColor); valueFormatStringBuilder.Append("{0}<C><S>"); entry.ValueFormat = valueFormatStringBuilder.ToString(); } entry.LastLimitState = limitState; } } } } if (updateVariables) { var colorVariablesStringBuilder = new StringBuilder(); _colorIndexDictionary.ForEach(pair => colorVariablesStringBuilder.Append($"<C{pair.Value}={pair.Key}>")); _rTSSService.SetFormatVariables(colorVariablesStringBuilder.ToString()); } }
protected override void DisposeResources() { //dispose the databases _databases.ForEach(x => x.Value.Dispose()); }
public async Task <List <BluetoothDevice> > FetchResultsAsync() { var running = true; var discoveryCanceled = false; while (running) { await new Select { Case(ChannelFactory.Timeout(TimeSpan.FromSeconds(30)), async() => { Console.WriteLine("Watchdog timeout at discovery!"); adapter.CancelDiscovery(); Console.WriteLine("Adapter enabled: " + adapter.IsEnabled); Console.WriteLine("Disabling adapter..."); adapter.Disable(); await Task.Delay(5000); Console.WriteLine("Enabling adapter..."); adapter.Enable(); await Task.Delay(10000); running = false; }), Case(intentChannel, intent => { Console.WriteLine($"GOT INTENT: " + intent.Action); var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice); switch (intent.Action) { case BluetoothAdapter.ActionDiscoveryStarted: if (state != 0) { Console.WriteLine("WARN: STATE IS " + state + " NOT 0"); } state = 1; Console.WriteLine($"Started Discovery"); break; case BluetoothDevice.ActionFound: if (state != 1 && state != 2) { Console.WriteLine("WARN: STATE IS " + state + " NOT 1 or 2"); } state = 2; Console.WriteLine($"Found: {device.Address} {device.Name ?? "[no name]"}"); if (device.Name == null) { Console.WriteLine("Skip as no name!"); return; } allDiscoveredDevicesByMac.TryAdd(device.Address, device); break; case BluetoothAdapter.ActionDiscoveryFinished: if (state != 2) { Console.WriteLine("WARN: STATE IS " + state + " NOT 2"); return; } state = 3; Console.WriteLine($"Finished Discovery, Performing Service Discovery for Filtering"); adapter.CancelDiscovery(); allDiscoveredDevicesByMac.ForEach(kvp => pendingServiceDiscoveryDevices.AddOrThrow(kvp.Value)); running = TriggerNextServiceDiscoveryElseCompletion(); break; case BluetoothDevice.ActionUuid: if (state != 3 && state != 4) { Console.WriteLine("WARN: STATE IS " + state + " NOT 3 or 4"); } state = 4; Console.WriteLine($"Got UUIDs of device {device.Address} {device.Name ?? "[no name]"}"); var uuidObjects = intent.GetParcelableArrayExtra(BluetoothDevice.ExtraUuid); if (uuidObjects != null) { var uuids = uuidObjects.Cast <ParcelUuid>().ToArray(); uuids.ForEach(Console.WriteLine); // Equality isn't implemented by uuid, so compare tostrings... if (uuids.Any(uuid => uuid.ToString().Equals(CampfireNetBluetoothConstants.APP_UUID.ToString())) || uuids.Any(uuid => uuid.ToString().Equals(CampfireNetBluetoothConstants.FIRMWARE_BUG_REVERSE_APP_UUID.ToString()))) { Console.WriteLine($"Found CampfireNet device {device.Address} {device.Name ?? "[no name]"}"); BluetoothDevice existing; if (discoveredCampfireNetDevices.TryGetValue(device.Address, out existing)) { Console.WriteLine("Device already discovered!"); } else { discoveredCampfireNetDevices.TryAdd(device.Address, device); } } } if (!allDiscoveredDevicesByMac.ContainsKey(device.Address)) { Console.WriteLine("Unrequested UUID, so tossing"); return; } if (serviceDiscoveredDevicesByMac.TryAdd(device.Address, device)) { running = TriggerNextServiceDiscoveryElseCompletion(); } break; default: throw new NotImplementedException($"Unhandled intent action: {intent.Action}"); } }) }.ConfigureAwait(false); } Console.WriteLine("Returning discovered list. Count: " + discoveredCampfireNetDevices.Values.ToList().Count); return(discoveredCampfireNetDevices.Values.ToList()); }
private static void InitializeFunctions() { // public static methods only var methods = typeof(Methods).GetMethods(BindingFlags.Static | BindingFlags.Public); var funcs = new ConcurrentDictionary<string, ConcurrentBag<UberScriptFunction>>(); Parallel.ForEach( methods, m => { var p = m.GetParameters(); // Always expect first parameter to be a trigger object. // Skip methods where names don't match rules: uppercase, optional digit, optional _ if (p.Length == 0 || !p[0].ParameterType.IsEqual<TriggerObject>() || !m.Name.All(n => Char.IsUpper(n) || Char.IsDigit(n) || n == '_')) { return; } var usf = new UberScriptFunction(m); funcs.AddOrUpdate( m.Name, s => new ConcurrentBag<UberScriptFunction> { usf }, (s, l) => { l.Add(usf); return l; }); }); Functions.Clear(); int count = 0, overloaded = 0; funcs.ForEach( (k, l) => { var v = l.ToArray(); if (v.Length == 0) { return; } ++count; overloaded += v.Length - 1; //Console.WriteLine("[UberScript]: {0}({1})", k, v.Length); Functions.Add(k, v); }); Console.WriteLine("[UberScript]: Initialized {0} functions and {1} overloads!", count, overloaded); }
private void WriteLastEtagsForCollections() { TransactionalStorage.Batch(accessor => lastCollectionEtags.ForEach(x => accessor.Lists.Set("Raven/Collection/Etag", x.Key, RavenJObject.FromObject(new { Etag = x.Value }), UuidType.Documents))); }
public override void FinishedInitialization() { singletons.ForEach(kvp => kvp.Value.FinishedInitialization()); }
public void ShowModificationImportWindowDialog(string modificationPath) { var rootNodeViewModel = modificationImportViewModelFactory.FromDirectory(modificationPath); var solution = riotSolutionLoader.Load(@"V:\Riot Games\League of Legends\RADS", RiotProjectType.AirClient | RiotProjectType.GameClient); var airResolver = new Resolver(solution.ProjectsByType[RiotProjectType.AirClient].ReleaseManifest.Root); var gameResolver = new Resolver(solution.ProjectsByType[RiotProjectType.GameClient].ReleaseManifest.Root); var fileNodes = rootNodeViewModel.EnumerateFileNodes().ToArray(); var importWindow = new ModificationImportWindow(); var modificationImportViewModel = new ModificationImportViewModel(this, importWindow, rootNodeViewModel); modificationImportViewModel.ModificationFriendlyName = fileSystemProxy.GetDirectoryInfo(modificationPath).Name; importWindow.DataContext = modificationImportViewModel; new Thread(() => { foreach (var fileNode in fileNodes) { var path = fileNode.Path; var airResolution = airResolver.Resolve(path); if (airResolution.Any()) { fileNode.ResolutionPath = airResolution.First().GetPath(); fileNode.ResolutionState = ResolutionState.ResolutionSuccessful; } else { var gameResolutions = gameResolver.Resolve(path); if (gameResolutions.Any()) { fileNode.ResolutionPath = gameResolutions.First().GetPath(); fileNode.ResolutionState = ResolutionState.ResolutionSuccessful; } else { fileNode.ResolutionState = ResolutionState.ResolutionFailed; } } } LeagueModificationCategory modificationType = LeagueModificationCategory.Other; if (fileNodes.Any(node => node.ResolutionState == ResolutionState.ResolutionSuccessful)) { var modificationTypeCounts = new ConcurrentDictionary<LeagueModificationCategory, int>(); foreach (var file in fileNodes) { if (file.ResolutionState == ResolutionState.ResolutionSuccessful) { if (file.ResolutionPath.IndexOf("DATA/Characters", StringComparison.OrdinalIgnoreCase) != -1 || file.ResolutionPath.IndexOf("assets/images/champions", StringComparison.OrdinalIgnoreCase) != -1) { if (file.ResolutionPath.IndexOf("ward", StringComparison.OrdinalIgnoreCase) != -1) { modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.Ward, 1, (existing, count) => count + 1); } else { modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.Champion, 1, (existing, count) => count + 1); } } else if (file.ResolutionPath.IndexOf("LEVELS") != -1) { modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.Map, 1, (existing, count) => count + 1); } else if (file.ResolutionPath.IndexOf("Menu", StringComparison.OrdinalIgnoreCase) != -1) { modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.UserInterface, 1, (existing, count) => count + 1); } else { modificationTypeCounts.AddOrUpdate(LeagueModificationCategory.Other, 1, (existing, count) => count + 1); } } } var categorizationCounts = modificationTypeCounts.Sum(x => x.Value); var highestCategorization = modificationTypeCounts.MaxBy(key => key.Value, Comparer<int>.Default); if (highestCategorization.Value >= categorizationCounts * 2.0 / 3.0) { modificationType = modificationTypeCounts.MaxBy(key => key.Value, Comparer<int>.Default).Key; } Console.WriteLine("Highest categorization: " + highestCategorization.Key.Name); modificationTypeCounts.ForEach(x => Console.WriteLine(x.Key.Name + ": " + x.Value)); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Send, new Action(() => { modificationImportViewModel.ModificationCategorization = modificationType; })); } }).Start(); importWindow.ShowDialog(); }