Here are the examples of the csharp api System.Collections.Generic.HashSet.Clear() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1644 Examples
19
Source : 071_unknown_quality_in_profile.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public void Commit()
{
foreach (var profile in _changedProfiles)
{
using (var updateProfileCmd = _connection.CreateCommand())
{
updateProfileCmd.Transaction = _transaction;
updateProfileCmd.CommandText = "UPDATE Profiles SET Name = ?, Cutoff = ?, Items = ?, Language = ? WHERE Id = ?";
updateProfileCmd.AddParameter(profile.Name);
updateProfileCmd.AddParameter(profile.Cutoff);
updateProfileCmd.AddParameter(profile.Items.ToJson());
updateProfileCmd.AddParameter(profile.Language);
updateProfileCmd.AddParameter(profile.Id);
updateProfileCmd.ExecuteNonQuery();
}
}
_changedProfiles.Clear();
}
19
Source : DirtyIndexPicker.cs
with MIT License
from BorisTheBrave
with MIT License
from BorisTheBrave
public void Reset()
{
dirtyIndices.Clear();
}
19
Source : BpViewModel.cs
with MIT License
from Bphots
with MIT License
from Bphots
public void Handle(ItemSelectedMessage message)
{
try
{
if (message.ItemInfo == null)
{
if (IsAutoMode || BpStatus.CurrentStep <= 0)
return;
if (BpStatus.StepSelectedIndex.Any())
{
foreach (var i in _listBpSteps[BpStatus.CurrentStep])
{
var vm = HeroSelectorViewModels.First(v => v.Id == i);
vm.Selected = false;
vm.SelectedItemInfo = null;
}
BpStatus.StepSelectedIndex.Clear();
}
else
{
foreach (var i in _listBpSteps[BpStatus.CurrentStep])
{
var vm = HeroSelectorViewModels.First(v => v.Id == i);
vm.InteractionVisible = false;
}
BpStatus.CurrentStep--;
{
var i = _listBpSteps[BpStatus.CurrentStep].Last();
var vm = HeroSelectorViewModels.First(v => v.Id == i);
vm.Selected = false;
vm.SelectedItemInfo = null;
if (_listBpSteps[BpStatus.CurrentStep].Count > 1)
{
var vmSelected = HeroSelectorViewModels.First(v => v.Id != _listBpSteps[BpStatus.CurrentStep].First());
if (vmSelected != null)
BpStatus.StepSelectedIndex = new HashSet<int>() { vmSelected.Id };
else
BpStatus.StepSelectedIndex.Clear();
}
else
BpStatus.StepSelectedIndex.Clear();
}
}
InvokeScript("update", new List<Tuple<string, string>>
{
Tuple.Create("chose", string.Join("|",
HeroSelectorViewModels
.Where(vm => vm.SelectedItemInfo != null)
.Select(vm => vm.SelectedItemInfo.Id))),
Tuple.Create("map", BpStatus.Map),
Tuple.Create("lang", App.Language)
});
return;
}
var idList = new List<string>();
foreach (var vm in HeroSelectorViewModels)
{
if (vm.SelectedItemInfo != null)
idList.Add(vm.SelectedItemInfo.Id);
}
if (App.CustomConfigurationSettings.UploadBanSample && BanSteps.Contains(message.SelectorId) && !string.IsNullOrEmpty(message.ItemInfo?.Id) && message.ItemInfo.Id != "0")
{
if (_lastIds[message.SelectorId] != message.ItemInfo?.Id)
{
Task.Run(() => UploadSampleAsync(message.ItemInfo.Id, BanSteps.IndexOf(message.SelectorId)));
_lastIds[message.SelectorId] = message.ItemInfo?.Id;
}
}
InvokeScript("update", new List<Tuple<string, string>>
{
Tuple.Create("chose", string.Join("|", idList)),
Tuple.Create("map", BpStatus.Map),
Tuple.Create("lang", App.Language)
});
if (BpStatus.StepSelectedIndex.Contains(message.SelectorId) || // 修改本轮选过的英雄
!_listBpSteps[BpStatus.CurrentStep].Contains(message.SelectorId)) // 修改其他轮选过的英雄
{
// 修改英雄选择,无需处理
}
else
{
// 新英雄选择,判断本轮是否已选够英雄
BpStatus.StepSelectedIndex.Add(message.SelectorId);
if (BpStatus.StepSelectedIndex.Count == _listBpSteps[BpStatus.CurrentStep].Count)
{
// 选够了,下一步
if (BpStatus.CurrentStep < 11)
{
BpStatus.CurrentStep++;
ProcessStep();
}
}
}
}
catch (Exception)
{
// TODO Ignore for test, please remove the catch
}
}
19
Source : TumbleBitManager.cs
with MIT License
from BreezeHub
with MIT License
from BreezeHub
public void ProcessBlock(int height, Block block)
{
// TODO: This double spend removal logic should be incorporated into the wallet
if (this.TumblingState.OriginWallet != null && this.TumblingState.DestinationWallet != null)
{
this.logger.LogDebug("Checking origin/destination wallets for double spends");
// Examine origin wallet for transactions that were erroneously included.
// Specifically, those spending inputs that have been spent by transactions
// in the destination wallet. This would otherwise frequently happen with
// the ClientRedeem transaction in particular.
HashSet<OutPoint> inputsSpent = new HashSet<OutPoint>();
HashSet<TransactionData> txToRemove = new HashSet<TransactionData>();
// Build cache of prevOuts from confirmed destination wallet transactions
// TODO: This can probably be substantially optimised, e.g. make cache persistent between blocks
foreach (TransactionData destTx in this.TumblingState.DestinationWallet.GetAllTransactionsByCoinType(
this.TumblingState.CoinType))
{
foreach (TxIn input in destTx.Transaction.Inputs)
{
inputsSpent.Add(input.PrevOut);
}
}
// Now check inputs of unconfirmed transactions in origin wallet.
// It is implicitly replacedumed that a confirmed transaction is usually not double spending.
foreach (TransactionData originTx in this.TumblingState.OriginWallet.GetAllTransactionsByCoinType(
this.TumblingState.CoinType))
{
if (originTx.IsConfirmed())
continue;
foreach (TxIn input in originTx.Transaction.Inputs)
{
if (inputsSpent.Contains(input.PrevOut))
{
this.logger.LogDebug($"Found double spend in origin wallet with txid {originTx.Id} spending {input.PrevOut.Hash} index {input.PrevOut.N}");
txToRemove.Add(originTx);
}
}
}
// Now remove the transactions identified as double spends from the origin wallet
foreach (TransactionData tx in txToRemove)
{
this.logger.LogDebug($"Detected double spend transaction in origin wallet, deleting {tx.Id}");
foreach (HdAccount account in this.TumblingState.OriginWallet.GetAccountsByCoinType(
this.TumblingState.CoinType))
{
foreach (HdAddress address in account.FindAddressesForTransaction(transaction =>
transaction.Id == tx.Id))
{
address.Transactions.Remove(tx);
}
}
}
// Now perform the same operation the other way around - there
// can also be unconfirmed transactions in the destination that
// double spend transactions in the source wallet
inputsSpent.Clear();
txToRemove.Clear();
// Build cache of prevOuts from confirmed origin wallet transactions
// TODO: This can probably be substantially optimised, e.g. make cache persistent between blocks
foreach (TransactionData originTx in this.TumblingState.OriginWallet.GetAllTransactionsByCoinType(
this.TumblingState.CoinType))
{
foreach (TxIn input in originTx.Transaction.Inputs)
{
inputsSpent.Add(input.PrevOut);
}
}
// Now check inputs of unconfirmed transactions in destination wallet.
// It is implicitly replacedumed that a confirmed transaction is usually not double spending.
foreach (TransactionData destTx in this.TumblingState.DestinationWallet.GetAllTransactionsByCoinType(
this.TumblingState.CoinType))
{
if (destTx.IsConfirmed())
continue;
foreach (TxIn input in destTx.Transaction.Inputs)
{
if (inputsSpent.Contains(input.PrevOut))
{
this.logger.LogDebug($"Found double spend in destination wallet with txid {destTx.Id} spending {input.PrevOut.Hash} index {input.PrevOut.N}");
txToRemove.Add(destTx);
}
}
}
// Now remove the transactions identified as double spends from the destination wallet
foreach (TransactionData tx in txToRemove)
{
foreach (HdAccount account in this.TumblingState.DestinationWallet.GetAccountsByCoinType(
this.TumblingState.CoinType))
{
foreach (HdAddress address in account.FindAddressesForTransaction(transaction =>
transaction.Id == tx.Id))
{
address.Transactions.Remove(tx);
}
}
}
// Now check for other transactions within the same wallet that spend the same input as each transaction
txToRemove.Clear();
foreach (TransactionData originTx in this.TumblingState.OriginWallet.GetAllTransactionsByCoinType(this.TumblingState.CoinType))
{
if (originTx.IsConfirmed())
continue;
foreach (TransactionData comparedTx in this.TumblingState.OriginWallet.GetAllTransactionsByCoinType(this.TumblingState.CoinType))
{
if (originTx.Id == comparedTx.Id)
continue;
foreach (TxIn input in originTx.Transaction.Inputs)
{
foreach (TxIn comparedTxInput in originTx.Transaction.Inputs)
{
if (input.PrevOut == comparedTxInput.PrevOut)
{
this.logger.LogDebug($"Detected unconfirmed double spend transaction in origin wallet, deleting {originTx.Id}");
txToRemove.Add(originTx);
}
}
}
}
}
foreach (TransactionData tx in txToRemove)
{
foreach (HdAccount account in this.TumblingState.OriginWallet.GetAccountsByCoinType(this.TumblingState.CoinType))
{
foreach (HdAddress address in account.FindAddressesForTransaction(transaction => transaction.Id == tx.Id))
{
address.Transactions.Remove(tx);
}
}
}
txToRemove.Clear();
foreach (TransactionData destTx in this.TumblingState.DestinationWallet.GetAllTransactionsByCoinType(this.TumblingState.CoinType))
{
if (destTx.IsConfirmed())
continue;
foreach (TransactionData comparedTx in this.TumblingState.DestinationWallet.GetAllTransactionsByCoinType(this.TumblingState.CoinType))
{
if (destTx.Id == comparedTx.Id)
continue;
foreach (TxIn input in destTx.Transaction.Inputs)
{
foreach (TxIn comparedTxInput in destTx.Transaction.Inputs)
{
if (input.PrevOut == comparedTxInput.PrevOut)
{
this.logger.LogDebug($"Detected unconfirmed double spend transaction in destination wallet, deleting {destTx.Id}");
txToRemove.Add(destTx);
}
}
}
}
}
foreach (TransactionData tx in txToRemove)
{
foreach (HdAccount account in this.TumblingState.DestinationWallet.GetAccountsByCoinType(this.TumblingState.CoinType))
{
foreach (HdAddress address in account.FindAddressesForTransaction(transaction => transaction.Id == tx.Id))
{
address.Transactions.Remove(tx);
}
}
}
}
// TumbleBit housekeeping
this.TumblingState.LastBlockReceivedHeight = height;
this.TumblingState.Save();
}
19
Source : MipsDebugger.cs
with MIT License
from bryanperris
with MIT License
from bryanperris
public void ClearBreakpoints() {
m_InstByAddressBreakpoints.Clear();
m_GPRWriteBreakpoints.Clear();
m_BranchBreakpoints.Clear();
m_InstByCodeBreakpoints.Clear();
}
19
Source : RegUsageCollector.cs
with MIT License
from bryanperris
with MIT License
from bryanperris
public void Reset()
{
m_UniqueGprSet.Clear();
m_UniqueCp0Set.Clear();
m_UniqueFprDSet.Clear();
m_UniqueFprFSet.Clear();
Hi = false;
Lo = false;
Fcr = false;
Address = false;
}
19
Source : DerivationSchemeParser.cs
with MIT License
from btcpayserver
with MIT License
from btcpayserver
public DerivationStrategyBase Parse(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
str = str.Trim();
HashSet<string> hintedLabels = new HashSet<string>();
if (!Network.Consensus.SupportSegwit)
{
hintedLabels.Add("legacy");
str = str.Replace("-[p2sh]", string.Empty, StringComparison.OrdinalIgnoreCase);
}
try
{
return BtcPayNetwork.NBXplorerNetwork.DerivationStrategyFactory.Parse(str);
}
catch
{
}
var parts = str.Split('-');
bool hasLabel = false;
for (int i = 0; i < parts.Length; i++)
{
if (IsLabel(parts[i]))
{
if (!hasLabel)
{
hintedLabels.Clear();
if (!Network.Consensus.SupportSegwit)
hintedLabels.Add("legacy");
}
hasLabel = true;
hintedLabels.Add(parts[i].Substring(1, parts[i].Length - 2).ToLowerInvariant());
continue;
}
try
{
var data = Network.GetBase58CheckEncoder().DecodeData(parts[i]);
if (data.Length < 4)
continue;
var prefix = Utils.ToUInt32(data, false);
var standardPrefix = Utils.ToBytes(0x0488b21eU, false);
for (int ii = 0; ii < 4; ii++)
data[ii] = standardPrefix[ii];
var derivationScheme = GetBitcoinExtPubKeyByNetwork(Network, data).ToString();
if (BtcPayNetwork.ElectrumMapping.TryGetValue(prefix, out var type))
{
switch (type)
{
case DerivationType.Legacy:
hintedLabels.Add("legacy");
break;
case DerivationType.SegwitP2SH:
hintedLabels.Add("p2sh");
break;
}
}
parts[i] = derivationScheme;
}
catch { continue; }
}
str = string.Join('-', parts.Where(p => !IsLabel(p)));
foreach (var label in hintedLabels)
{
str = $"{str}-[{label}]";
}
return BtcPayNetwork.NBXplorerNetwork.DerivationStrategyFactory.Parse(str);
}
19
Source : RateRules.cs
with MIT License
from btcpayserver
with MIT License
from btcpayserver
public bool Reevaluate()
{
_BidAsk = null;
_EvaluatedNode = null;
_Evaluated = null;
Errors.Clear();
var rewriter = new ReplaceExchangeRateRewriter();
rewriter.Rates = ExchangeRates;
var result = rewriter.Visit(this.expression);
foreach (var item in rewriter.Errors)
{
Errors.Add(item);
}
_Evaluated = result.NormalizeWhitespace("", "\n").ToString();
if (HasError)
return false;
var calculate = new CalculateWalker();
calculate.Visit(result);
if (calculate.Values.Count != 1 || calculate.Errors.Count != 0)
{
foreach (var item in calculate.Errors)
{
Errors.Add(item);
}
return false;
}
_BidAsk = calculate.Values.Pop();
_EvaluatedNode = result;
return true;
}
19
Source : Octree.cs
with GNU General Public License v3.0
from BudgetToaster
with GNU General Public License v3.0
from BudgetToaster
public void Rebuild()
{
var capacity = Mathf.NextPowerOfTwo(_data.Count - _freeStructureMemory.Count * 8 - _freeAttributeMemory.Count);
var optimizedData = new List<int>(capacity);
void RebuildBranch(int referenceBranchPtr)
{
var start = optimizedData.Count;
optimizedData.AddRange(new int[8]);
for (var i = 0; i < 8; i++)
{
if (_data[referenceBranchPtr + i] == 1 << 31)
{
optimizedData[start + i] = 1 << 31;
}
else if ((_data[referenceBranchPtr + i] >> 31 & 1) == 1)
{
optimizedData[start + i] = 1 << 31 | optimizedData.Count;
var attribPtr = _data[referenceBranchPtr + i] & 0x7FFFFFFF;
var c = (_data[attribPtr] >> 24) & 0xFF;
for(var j = 0; j < c; j++)
optimizedData.Add(_data[attribPtr + j]);
}
else
{
optimizedData[start + i] = optimizedData.Count;
RebuildBranch(_data[referenceBranchPtr + i]);
}
}
}
if (_data[0] == 1 << 31)
{
optimizedData.Add(1 << 31);
}
else if ((_data[0] >> 31 & 1) == 1)
{
optimizedData.Add(1 << 31 | (optimizedData.Count + 1));
var attribPtr = _data[0] & 0x7FFFFFFF;
var c = (_data[attribPtr] >> 24) & 0xFF;
for(var j = 0; j < c; j++)
optimizedData.Add(_data[attribPtr + j]);
}
else
{
optimizedData.Add(optimizedData.Count + 1);
RebuildBranch(_data[0]);
}
_data = optimizedData;
_ptrStackDepth = 0;
_ptrStackPos = Vector3.one;
_ptrStack = new int[24];
_freeAttributeMemory.Clear();
_freeStructureMemory.Clear();
_lastApply = new ulong[2048];
for (var i = 0; i < _lastApply.Length; i++)
_lastApply[i] = ulong.MaxValue;
}
19
Source : GUIHelper.cs
with MIT License
from cabarius
with MIT License
from cabarius
public static ToggleState ToggleTypeList(ToggleState toggle, string text, HashSet<string> selectedTypes, HashSet<Type> allTypes, GUIStyle style = null, params GUILayoutOption[] options) {
GUILayout.BeginHorizontal();
UI.ToggleButton(ref toggle, text, style, options);
if (toggle.IsOn()) {
using (new GUILayout.VerticalScope()) {
using (new GUILayout.HorizontalScope()) {
if (GUILayout.Button("Select All")) {
foreach (var type in allTypes) {
selectedTypes.Add(type.FullName);
}
}
if (GUILayout.Button("Deselect All")) {
selectedTypes.Clear();
}
}
foreach (var type in allTypes) {
ToggleButton(selectedTypes.Contains(type.FullName) ? ToggleState.On : ToggleState.Off, type.Name.ToSentence(),
() => selectedTypes.Add(type.FullName),
() => selectedTypes.Remove(type.FullName),
style, options);
}
}
}
GUILayout.EndHorizontal();
return toggle;
}
19
Source : Settings+Multiclass.cs
with MIT License
from cabarius
with MIT License
from cabarius
public void AddExclusive(BlueprintArchetype arch) { Clear(); Add(arch); }
19
Source : RequirementCheck.cs
with GNU General Public License v2.0
from Caeden117
with GNU General Public License v2.0
from Caeden117
internal static void Setup()
{
requirementsAndSuggestions.Clear();
RegisterRequirement(new ChromaReq());
RegisterRequirement(new LegacyChromaReq());
RegisterRequirement(new MappingExtensionsReq());
RegisterRequirement(new NoodleExtensionsReq());
RegisterRequirement(new CinemaReq());
RegisterRequirement(new SoundExtensionsReq());
}
19
Source : SelectionController.cs
with GNU General Public License v2.0
from Caeden117
with GNU General Public License v2.0
from Caeden117
public void Copy(bool cut = false)
{
if (!HreplacedelectedObjects()) return;
CopiedObjects.Clear();
var firstTime = SelectedObjects.OrderBy(x => x.Time).First().Time;
foreach (var data in SelectedObjects)
{
var collection = BeatmapObjectContainerCollection.GetCollectionForType(data.BeatmapType);
if (collection.LoadedContainers.TryGetValue(data, out var con)) con.SetOutlineColor(instance.copiedColor);
var copy = BeatmapObject.GenerateCopy(data);
copy.Time -= firstTime;
CopiedObjects.Add(copy);
}
if (cut) Delete();
var bpmChanges =
BeatmapObjectContainerCollection.GetCollectionForType<BPMChangesContainer>(BeatmapObject.ObjectType.BpmChange);
var lastBpmChange = bpmChanges.FindLastBpm(atsc.CurrentBeat);
copiedBpm = lastBpmChange?.Bpm ?? atsc.Song.BeatsPerMinute;
}
19
Source : BoxSelectionPlacementController.cs
with GNU General Public License v2.0
from Caeden117
with GNU General Public License v2.0
from Caeden117
public override void OnPhysicsRaycast(Intersections.IntersectionHit hit, Vector3 transformedPoint)
{
previoureplaced = hit;
transformed = transformedPoint;
var roundedHit = ParentTrack.InverseTransformPoint(hit.Point);
roundedHit = new Vector3(
Mathf.Ceil(Math.Min(Math.Max(roundedHit.x, Bounds.min.x + 0.01f), Bounds.max.x)),
Mathf.Ceil(Math.Min(Math.Max(roundedHit.y, 0.01f), 3f)),
roundedHit.z
);
instantiatedContainer.transform.localPosition = roundedHit - new Vector3(0.5f, 1, 0);
if (!IsSelecting)
{
Bounds = default;
selectedTypes.Clear();
TestForType<EventPlacement>(hit, BeatmapObject.ObjectType.Event);
TestForType<NotePlacement>(hit, BeatmapObject.ObjectType.Note);
TestForType<ObstaclePlacement>(hit, BeatmapObject.ObjectType.Obstacle);
TestForType<CustomEventPlacement>(hit, BeatmapObject.ObjectType.CustomEvent);
TestForType<BPMChangePlacement>(hit, BeatmapObject.ObjectType.BpmChange);
instantiatedContainer.transform.localScale = Vector3.right + Vector3.up;
var localScale = instantiatedContainer.transform.localScale;
var localpos = instantiatedContainer.transform.localPosition;
instantiatedContainer.transform.localPosition -= new Vector3(localScale.x / 2, 0, 0);
}
else
{
var originShove = originPos;
float xOffset = 0;
float yOffset = 0;
// When moving from right to left, move the origin to the right and make
// the selection larger as the origin points are on the left
if (roundedHit.x <= originPos.x + 1)
{
xOffset = -1;
originShove.x += 1;
}
if (roundedHit.y <= originPos.y)
{
yOffset = -1;
originShove.y += 1;
}
instantiatedContainer.transform.localPosition = originShove;
var newLocalScale = roundedHit + new Vector3(xOffset, yOffset, 0.5f) - originShove;
var newLocalScaleY = Mathf.Max(newLocalScale.y, 1);
if (yOffset < 0) newLocalScaleY = Mathf.Min(-1, newLocalScale.y);
newLocalScale = new Vector3(newLocalScale.x, newLocalScaleY, newLocalScale.z);
instantiatedContainer.transform.localScale = newLocalScale;
var startBeat = instantiatedContainer.transform.localPosition.z / EditorScaleController.EditorScale;
var endBeat = (instantiatedContainer.transform.localPosition.z + newLocalScale.z) /
EditorScaleController.EditorScale;
if (startBeat > endBeat) (startBeat, endBeat) = (endBeat, startBeat);
SelectionController.ForEachObjectBetweenTimeByGroup(startBeat, endBeat, true, true, true, (bocc, bo) =>
{
if (!selectedTypes.Contains(bo.BeatmapType)) return; // Must be a type we can select
var left = instantiatedContainer.transform.localPosition.x +
instantiatedContainer.transform.localScale.x;
var right = instantiatedContainer.transform.localPosition.x;
if (right < left) (left, right) = (right, left);
var top = instantiatedContainer.transform.localPosition.y +
instantiatedContainer.transform.localScale.y;
var bottom = instantiatedContainer.transform.localPosition.y;
if (top < bottom) (top, bottom) = (bottom, top);
var p = new Vector2(left, bottom);
if (bo is IBeatmapObjectBounds obj)
{
p = obj.GetCenter();
}
else if (bo is MapEvent evt)
{
var position = evt.GetPosition(Labels, EventsContainer.PropagationEditing,
EventsContainer.EventTypeToPropagate);
// Not visible = notselectable
if (position == null) return;
p = new Vector2(position?.x + Bounds.min.x ?? 0, position?.y ?? 0);
}
else if (bo is BeatmapCustomEvent custom)
{
p = new Vector2(CustomCollection.CustomEventTypes.IndexOf(custom.Type) + Bounds.min.x + 0.5f,
0.5f);
}
// Check if calculated position is outside bounds
if (p.x < left || p.x > right || p.y < bottom || p.y >= top) return;
if (!alreadySelected.Contains(bo) && selected.Add(bo))
SelectionController.Select(bo, true, false, false);
});
foreach (var combinedObj in SelectionController.SelectedObjects.ToArray())
{
if (!selected.Contains(combinedObj) && !alreadySelected.Contains(combinedObj))
SelectionController.Deselect(combinedObj, false);
}
selected.Clear();
}
}
19
Source : BoxSelectionPlacementController.cs
with GNU General Public License v2.0
from Caeden117
with GNU General Public License v2.0
from Caeden117
private IEnumerator WaitABitreplacedOffOtherPlacementControllers()
{
yield return new WaitForSeconds(0.1f);
IsSelecting = false;
selected.Clear(); // oh replaced turned out i didnt need to rewrite the whole thing, just move it over here
OnPhysicsRaycast(previoureplaced, transformed);
}
19
Source : SelectionController.cs
with GNU General Public License v2.0
from Caeden117
with GNU General Public License v2.0
from Caeden117
private void Start()
{
instance = this;
SelectedObjects.Clear();
}
19
Source : ComponentRegistry.cs
with MIT License
from cake-build
with MIT License
from cake-build
public void Dispose()
{
foreach (var registration in _registrations)
{
registration.Value.Clear();
}
_registrations.Clear();
}
19
Source : TradierBrokerage.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private void CheckForFills()
{
// reentrance guard
if (!Monitor.TryEnter(_fillLock))
{
return;
}
try
{
var intradayAndPendingOrders = GetIntradayAndPendingOrders();
if (intradayAndPendingOrders == null)
{
Log.Error("TradierBrokerage.CheckForFills(): Returned null response!");
return;
}
var updatedOrders = intradayAndPendingOrders.ToDictionary(x => x.Id);
// loop over our cache of orders looking for changes in status for fill quanreplacedies
foreach (var cachedOrder in _cachedOpenOrdersByTradierOrderID)
{
TradierOrder updatedOrder;
var hasUpdatedOrder = updatedOrders.TryGetValue(cachedOrder.Key, out updatedOrder);
if (hasUpdatedOrder)
{
// determine if the order has been updated and produce fills accordingly
ProcessPotentiallyUpdatedOrder(cachedOrder.Value, updatedOrder);
// if the order is still open, update the cached value
if (!OrderIsClosed(updatedOrder)) UpdateCachedOpenOrder(cachedOrder.Key, updatedOrder);
continue;
}
// if we made it here this may be a canceled order via another portal, so we need to figure this one
// out with its own rest call, do this async to not block this thread
if (!_reentranceGuardByTradierOrderID.Add(cachedOrder.Key))
{
// we don't want to reenter this task, so we'll use a hashset to keep track of what orders are currently in there
continue;
}
var cachedOrderLocal = cachedOrder;
Task.Run(() =>
{
try
{
var updatedOrderLocal = GetOrder(cachedOrderLocal.Key);
if (updatedOrderLocal == null)
{
Log.Error($"TradierBrokerage.CheckForFills(): Unable to locate order {cachedOrderLocal.Key} in cached open orders.");
throw new InvalidOperationException("TradierBrokerage.CheckForFills(): GetOrder() return null response");
}
UpdateCachedOpenOrder(cachedOrderLocal.Key, updatedOrderLocal);
ProcessPotentiallyUpdatedOrder(cachedOrderLocal.Value, updatedOrderLocal);
}
catch (Exception err)
{
Log.Error(err);
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "PendingOrderNotReturned",
"An error occurred while trying to resolve fill events from Tradier orders: " + err));
}
finally
{
// signal that we've left the task
_reentranceGuardByTradierOrderID.Remove(cachedOrderLocal.Key);
}
});
}
// if we get order updates for orders we're unaware of we need to bail, this can corrupt the algorithm state
var unknownOrderIDs = updatedOrders.Where(IsUnknownOrderID).ToHashSet(x => x.Key);
unknownOrderIDs.ExceptWith(_verifiedUnknownTradierOrderIDs);
var fireTask = unknownOrderIDs.Count != 0 && _unknownTradierOrderIDs.Count == 0;
foreach (var unknownOrderID in unknownOrderIDs)
{
_unknownTradierOrderIDs.Add(unknownOrderID);
}
if (fireTask)
{
// wait a second and then check the order provider to see if we have these broker IDs, maybe they came in later (ex, symbol denied for short trading)
Task.Delay(TimeSpan.FromSeconds(2)).ContinueWith(t =>
{
var localUnknownTradierOrderIDs = _unknownTradierOrderIDs.ToHashSet();
_unknownTradierOrderIDs.Clear();
try
{
// verify we don't have them in the order provider
Log.Trace("TradierBrokerage.CheckForFills(): Verifying missing brokerage IDs: " + string.Join(",", localUnknownTradierOrderIDs));
var orders = localUnknownTradierOrderIDs.Select(x => _orderProvider.GetOrderByBrokerageId(x)).Where(x => x != null);
var stillUnknownOrderIDs = localUnknownTradierOrderIDs.Where(x => !orders.Any(y => y.BrokerId.Contains(x.ToStringInvariant()))).ToList();
if (stillUnknownOrderIDs.Count > 0)
{
// fetch all rejected intraday orders within the last minute, we're going to exclude rejected orders from the error condition
var recentOrders = GetIntradayAndPendingOrders().Where(x => x.Status == TradierOrderStatus.Rejected)
.Where(x => DateTime.UtcNow - x.TransactionDate < TimeSpan.FromMinutes(1)).ToHashSet(x => x.Id);
// remove recently rejected orders, sometimes we'll get updates for these but we've already marked them as rejected
stillUnknownOrderIDs.RemoveAll(x => recentOrders.Contains(x));
if (stillUnknownOrderIDs.Count > 0)
{
// if we still have unknown IDs then we've gotta bail on the algorithm
var ids = string.Join(", ", stillUnknownOrderIDs);
Log.Error("TradierBrokerage.CheckForFills(): Unable to verify all missing brokerage IDs: " + ids);
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, "UnknownOrderId", "Received unknown Tradier order id(s): " + ids));
return;
}
}
foreach (var unknownTradierOrderID in localUnknownTradierOrderIDs)
{
// add these to the verified list so we don't check them again
_verifiedUnknownTradierOrderIDs.Add(unknownTradierOrderID);
}
Log.Trace("TradierBrokerage.CheckForFills(): Verified all missing brokerage IDs.");
}
catch (Exception err)
{
// we need to recheck these order ids since we failed, so add them back to the set
foreach (var id in localUnknownTradierOrderIDs) _unknownTradierOrderIDs.Add(id);
Log.Error(err);
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "UnknownIdResolution", "An error occurred while trying to resolve unknown Tradier order IDs: " + err));
}
});
}
}
catch (Exception err)
{
Log.Error(err);
OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "CheckForFillsError", "An error occurred while checking for fills: " + err));
}
finally
{
Monitor.Exit(_fillLock);
}
}
19
Source : InsightManager.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public IEnumerable<InsightreplacedysisContext> GetUpdatedContexts()
{
lock (_lock)
{
var copy = _updatedInsightContexts.ToList();
_updatedInsightContexts.Clear();
return copy;
}
}
19
Source : LogProfileSelectionDialog.axaml.cs
with MIT License
from carina-studio
with MIT License
from carina-studio
protected override void OnClosed(EventArgs e)
{
// detach from log profiles
((INotifyCollectionChanged)LogProfiles.All).CollectionChanged -= this.OnAllLogProfilesChanged;
foreach (var profile in this.attachedLogProfiles)
profile.PropertyChanged -= this.OnLogProdilePropertyChanged;
this.attachedLogProfiles.Clear();
// call base
base.OnClosed(e);
}
19
Source : LogProfiles.cs
with MIT License
from carina-studio
with MIT License
from carina-studio
public static async Task InitializeAsync(IULogViewerApplication app)
{
// check state
app.VerifyAccess();
if (LogProfiles.app != null && LogProfiles.app != app)
throw new InvalidOperationException();
// attach to application
LogProfiles.app = app;
app.StringsUpdated += OnApplicationStringsUpdated;
// create logger
logger = app.LoggerFactory.CreateLogger(nameof(LogProfiles));
// load more built-in profiles in debug mode
if (app.IsDebugMode)
{
builtInProfileIDs.Add("ULogViewerLog");
builtInProfileIDs.Add("ULogViewerMemoryLog");
}
// create scheduled action
saveProfilesAction = new ScheduledAction(async () =>
{
if (pendingSavingProfiles.IsEmpty())
return;
var profiles = pendingSavingProfiles.ToArray().Also(_ => pendingSavingProfiles.Clear());
logger?.LogDebug($"Start saving {profiles.Length} profile(s)");
foreach (var profile in profiles)
{
var fileName = profile.FileName;
try
{
if (fileName == null)
fileName = await profile.FindValidFileNameAsync(profilesDirectoryPath);
_ = profile.SaveAsync(fileName);
}
catch (Exception ex)
{
logger?.LogError(ex, $"Unable to save profile '{profile.Name}' to '{fileName}'");
}
}
logger?.LogDebug($"Complete saving {profiles.Length} profile(s)");
});
// create empty profile
emptyProfile = LogProfile.CreateEmptyBuiltInProfile(app);
// load build-in profiles
logger.LogDebug("Start loading built-in profiles");
var profileCount = 0;
foreach (var id in builtInProfileIDs)
{
logger.LogDebug($"Load '{id}'");
AttachToProfile(await LogProfile.LoadBuiltInProfileAsync(app, id));
++profileCount;
}
logger.LogDebug($"Complete loading {profileCount} built-in profile(s)");
// load profiles
profilesDirectoryPath = Path.Combine(app.RootPrivateDirectoryPath, "Profiles");
profileCount = 0;
logger.LogDebug("Start loading profiles");
var fileNames = await Task.Run(() =>
{
try
{
if (!Directory.Exists(profilesDirectoryPath))
return new string[0];
return Directory.GetFiles(profilesDirectoryPath, "*.json");
}
catch (Exception ex)
{
logger.LogError(ex, $"Unable to check profiles in directory '{profilesDirectoryPath}'");
return new string[0];
}
});
foreach (var fileName in fileNames)
{
try
{
AttachToProfile(await LogProfile.LoadProfileAsync(app, fileName));
++profileCount;
}
catch (Exception ex)
{
logger.LogError(ex, $"Unable to load profile from '{fileName}'");
}
}
logger.LogDebug($"Complete loading {profileCount} profile(s)");
}
19
Source : Assertion.cs
with Apache License 2.0
from casbin
with Apache License 2.0
from casbin
public void RefreshPolicyStringSet()
{
PolicyStringSet.Clear();
foreach (List<string> rule in Policy)
{
PolicyStringSet.Add(Utility.RuleToString(rule));
}
}
19
Source : Assertion.cs
with Apache License 2.0
from casbin
with Apache License 2.0
from casbin
internal void ClearPolicy()
{
Policy.Clear();
PolicyStringSet.Clear();
}
19
Source : Logger.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
public static void SetModes(params LogMode[] modes)
{
if (Modes.Count != 0)
{
Modes.Clear();
}
if (modes is null)
{
return;
}
foreach (var mode in modes)
{
Modes.Add(mode);
}
}
19
Source : DWorld.cs
with MIT License
from changshuang
with MIT License
from changshuang
public void Step(Fix32 delta) {
if (!simulate)
return;
contacts.Clear();
Fix32 invDelta = (delta > Fix32.Zero) ? (Fix32)1 / delta : Fix32.Zero;
//integrate forces
Profiler.BeginSample("Integrate forces");
foreach (DBody body in bodies) {
if (body.IsFixed())
continue;
integrator.IntegrateForces(body, delta);
}
Profiler.EndSample();
Profiler.BeginSample("Find collisions");
detector.FindCollisions(contacts);
Profiler.EndSample();
//init collision manifolds
foreach (Manifold contact in contacts) {
contact.Init(invDelta);
}
//resolve collisions
for (uint i = 0; i < ITERATIONS; i++) {
foreach (Manifold contact in contacts) {
contact.ApplyImpulse();
}
}
//integrate velocities
foreach (DBody body in bodies) {
if (body.IsFixed())
continue;
Profiler.BeginSample("Remove-Integrate-Insert");
detector.Remove(body);
integrator.IntegrateVelocities(body, delta);
detector.Insert(body);
Profiler.EndSample();
}
}
19
Source : VRTK_IndependentRadialMenuController.cs
with MIT License
from charles-river-analytics
with MIT License
from charles-river-analytics
protected override void Initialize()
{
if (eventsManager == null)
{
initialRotation = transform.localRotation;
UpdateEventsManager();
return; // If all goes well in updateEventsManager, it will then call Initialize again, skipping this if statement
}
// Reset variables
interactingObjects.Clear();
collidingObjects.Clear();
if (delayedSetColliderEnabledRoutine != null)
{
StopCoroutine(delayedSetColliderEnabledRoutine);
}
isClicked = false;
waitingToDisableCollider = false;
counter = 2;
if (transform.childCount == 0) // This means things haven't been properly initialized yet, will cause problems.
{
return;
}
float radius = (transform.GetChild(0).GetComponent<RectTransform>().rect.width / 2) * offsetMultiplier;
transform.localPosition = new Vector3(0, 0, radius);
if (addMenuCollider)
{
gameObject.SetActive(false); // Just be sure it doesn't briefly flash
transform.localScale = Vector3.one; // If this were left at zero it would ruin the transformations below
Quaternion startingRot = transform.rotation;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0)); // Rotation can mess up the calculations below
SphereCollider collider = eventsManager.gameObject.AddComponent<SphereCollider>();
// All of the transformVector's are to account for the scaling of the radial menu's 'panel' and the scaling of the eventsManager parent object
collider.radius = (transform.GetChild(0).GetComponent<RectTransform>().rect.width / 2) * colliderRadiusMultiplier * eventsManager.transform.InverseTransformVector(transform.GetChild(0).TransformVector(Vector3.one)).x;
collider.center = eventsManager.transform.InverseTransformVector(transform.position - eventsManager.transform.position);
collider.isTrigger = true;
collider.enabled = false; // Want this to only activate when the menu is showing
menuCollider = collider;
desiredColliderCenter = collider.center;
transform.rotation = startingRot;
}
if (!menu.isShown)
{
transform.localScale = Vector3.zero;
}
gameObject.SetActive(true);
}
19
Source : VRTK_BasePointerRenderer.cs
with MIT License
from charles-river-analytics
with MIT License
from charles-river-analytics
protected virtual void MakeRenderersVisible()
{
foreach (GameObject currentRenderer in new HashSet<GameObject>(makeRendererVisible))
{
ToggleRendererVisibility(currentRenderer, true);
}
makeRendererVisible.Clear();
}
19
Source : VRTK_InteractObjectAppearance.cs
with MIT License
from charles-river-analytics
with MIT License
from charles-river-analytics
protected virtual void OnEnable()
{
currentRenderStates.Clear();
currentGameObjectStates.Clear();
affectingRoutines.Clear();
nearTouchingObjects.Clear();
touchingObjects.Clear();
EnableListeners();
if (objectToAffect != null)
{
ToggleState(objectToAffect, gameObjectActiveByDefault, rendererVisibleByDefault, VRTK_InteractableObject.InteractionType.None);
}
}
19
Source : VRTK_BasePointerRenderer.cs
with MIT License
from charles-river-analytics
with MIT License
from charles-river-analytics
protected virtual void OnEnable()
{
cachedPointerAttachPoint = null;
cachedAttachedHand = SDK_BaseController.ControllerHand.None;
defaultMaterial = Resources.Load("WorldPointer") as Material;
makeRendererVisible.Clear();
CreatePointerOriginTransformFollow();
CreatePointerObjects();
}
19
Source : PassVariableLifetimes.cs
with GNU General Public License v3.0
from CheezLang
with GNU General Public License v3.0
from CheezLang
private void PreplacedVariableLifetimes(AstFuncExpr func)
{
mBreaks.Clear();
mMovedTempVars.Clear();
var symStatTable = new SymbolStatusTable(null);
foreach (var p in func.Parameters)
{
symStatTable.InitSymbolStatus(p, SymbolStatus.Kind.initialized, p);
}
if (func.ReturnTypeExpr?.Name != null)
{
symStatTable.InitSymbolStatus(func.ReturnTypeExpr, SymbolStatus.Kind.uninitialized, func.ReturnTypeExpr.Name);
}
if (func.ReturnTypeExpr?.TypeExpr is AstTupleExpr t && t.IsFullyNamed)
{
foreach (var m in t.Types)
{
symStatTable.InitSymbolStatus(m.Symbol, SymbolStatus.Kind.uninitialized, m.Name);
}
}
PreplacedVLExpr(func.Body, symStatTable);
// destruct params
if (!func.Body.GetFlag(ExprFlags.Returns))
{
for (int i = func.Parameters.Count - 1; i >= 0; i--)
{
var p = func.Parameters[i];
var stat = symStatTable.GetSymbolStatus(p);
if (stat.kind == SymbolStatus.Kind.initialized)
{
func.Body.AddDestruction(Destruct(p, func.Body.End));
}
}
}
}
19
Source : QsiActionAnalyzer.cs
with MIT License
from chequer-io
with MIT License
from chequer-io
[MethodImpl(MethodImplOptions.NoInlining)]
protected virtual IEnumerable<DataManipulationTargetColumnPivot> ResolveDataManipulationTargetColumns(QsiTableColumn declaredColumn, int declaredOrder)
{
if (declaredColumn.IsAnonymous)
throw new QsiException(QsiError.NotUpdatableColumn, "anonymous");
if (declaredColumn.IsBinding || declaredColumn.IsExpression || !declaredColumn.IsVisible)
throw new QsiException(QsiError.NotUpdatableColumn, declaredColumn.Name);
var queue = new Queue<QsiTableColumn>();
queue.Enqueue(declaredColumn);
HashSet<QsiTableColumn> recursiveTracing = null;
while (queue.TryDequeue(out var column))
{
bool skip = false;
recursiveTracing?.Clear();
while (column.Parent.Type != QsiTableType.Table)
{
var refCount = column.References.Count;
if (column.Parent.Type == QsiTableType.Join && refCount == 0 || refCount != 1)
throw new QsiException(QsiError.NotUpdatableColumn, declaredColumn.Name);
if (recursiveTracing?.Contains(column) ?? false)
throw new QsiException(QsiError.NotUpdatableColumn, declaredColumn.Name);
recursiveTracing ??= new HashSet<QsiTableColumn>();
recursiveTracing.Add(column);
if (column.Parent.Type is QsiTableType.Join or QsiTableType.Union)
{
foreach (var joinedColumn in column.References)
{
queue.Enqueue(joinedColumn);
}
skip = true;
break;
}
column = column.References[0];
}
if (skip)
continue;
yield return new DataManipulationTargetColumnPivot(
column.Parent.Columns.IndexOf(column),
column,
declaredOrder,
declaredColumn);
}
}
19
Source : QsiActionAnalyzer.cs
with MIT License
from chequer-io
with MIT License
from chequer-io
protected int FindColumnIndex(IreplacedyzerContext context, QsiTableStructure table, QsiQualifiedIdentifier identifier)
{
var alias = new QsiQualifiedIdentifier(identifier[..^1]);
var name = identifier[^1];
var queue = new Queue<QsiTableColumn>();
var recursiveTracker = new HashSet<QsiTableColumn>();
for (int i = 0; i < table.Columns.Count; i++)
{
if (!IdentifierComparer.Equals(table.Columns[i].Name, name))
continue;
if (identifier.Level == 1)
return i;
queue.Clear();
recursiveTracker.Clear();
queue.Enqueue(table.Columns[i]);
while (queue.TryDequeue(out var column))
{
recursiveTracker.Add(column);
if (column.Parent.HasIdentifier)
{
// * case - Explicit access
if (QualifiedIdentifierComparer.Equals(column.Parent.Identifier, alias))
return i;
// * case - N Level implicit access
if (context.Options.UseExplicitRelationAccess)
break;
if (!QsiUtility.IsReferenceType(column.Parent.Type))
break;
if (column.Parent.Identifier.Level <= identifier.Level)
break;
QsiIdentifier[] partialIdentifiers = column.Parent.Identifier[^identifier.Level..];
var partialIdentifier = new QsiQualifiedIdentifier(partialIdentifiers);
if (QualifiedIdentifierComparer.Equals(partialIdentifier, alias))
return i;
break;
}
foreach (var refColumn in column.References.Where(refColumn => !recursiveTracker.Contains(refColumn)))
{
queue.Enqueue(refColumn);
}
}
}
return -1;
}
19
Source : ConcurrentHashSet.cs
with MIT License
from chequer-io
with MIT License
from chequer-io
public void Clear()
{
_lock.EnterWriteLock();
try
{
_hashSet.Clear();
}
finally
{
if (_lock.IsWriteLockHeld)
_lock.ExitWriteLock();
}
}
19
Source : Texture.cs
with MIT License
from ChevyRay
with MIT License
from ChevyRay
internal static void UnbindMarked()
{
for (uint i = 0; i < binded.Length; ++i)
{
if (binded[i].ID != 0 && unbind.Contains(binded[i].ID))
{
GL.ActiveTexture(i);
GL.BindTexture(binded[i].Target, 0);
binded[i].ID = 0;
}
}
unbind.Clear();
}
19
Source : Texture.cs
with MIT License
from ChevyRay
with MIT License
from ChevyRay
internal static void UnbindAll()
{
unbind.Clear();
for (uint i = 0; i < binded.Length; ++i)
{
if (binded[i].ID != 0)
{
GL.ActiveTexture(i);
GL.BindTexture(binded[i].Target, 0);
binded[i].ID = 0;
}
}
}
19
Source : Keyboard.cs
with MIT License
from ChevyRay
with MIT License
from ChevyRay
internal static void PostUpdate()
{
pressed.Clear();
released.Clear();
repeated.Clear();
}
19
Source : JsEnv.cs
with MIT License
from chexiongsheng
with MIT License
from chexiongsheng
internal void ReleasePendingJSObjects()
{
lock (pendingReleaseObjs)
{
foreach(var nativeJsObjPtr in pendingReleaseObjs)
{
if (!jsObjectFactory.IsJsObjectAlive(nativeJsObjPtr))
{
PuertsDLL.ReleaseJSObject(isolate, nativeJsObjPtr);
}
}
pendingReleaseObjs.Clear();
}
}
19
Source : SphereCastVisualization.cs
with MIT License
from chillersanim
with MIT License
from chillersanim
void Update()
{
if (Input.GetKey(KeyCode.E))
{
Radius = Mathf.Clamp(Radius + 10 * Time.deltaTime, 1, 80);
}
if (Input.GetKey(KeyCode.Q))
{
Radius = Mathf.Clamp(Radius - 10 * Time.deltaTime, 1, 80);
}
currentPoints.Clear();
var center0 = this.transform.position - Vector3.right * Radius;
var center1 = this.transform.position + Vector3.right * Radius;
var shape = new VolumePlane(Vector3.Cross(this.transform.right - this.transform.up * 2, this.transform.forward), this.transform.position);
stopwatch.Restart();
currentPoints.AddRange(Point.AllPoints.ShapeCast(shape));
stopwatch.Stop();
CastTime = stopwatch.Elapsed.TotalMilliseconds / 1000.0;
previousPoints.ExceptWith(currentPoints);
foreach (var pp in previousPoints)
{
pp.SetActive(false);
}
previousPoints.Clear();
foreach (var cp in currentPoints)
{
cp.SetActive(true);
previousPoints.Add(cp);
}
if (Input.GetKeyDown(KeyCode.F))
{
foreach (var point in currentPoints)
{
var rb = point.GetComponent<Rigidbody>();
if (rb != null)
{
rb.AddExplosionForce(10f, this.transform.position, Radius, 0, ForceMode.Impulse);
}
}
}
}
19
Source : CollectVariablesVisitor.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public VisitorAction Enter(
OperationDefinitionNode node,
ISyntaxNode parent,
IReadOnlyList<object> path,
IReadOnlyList<ISyntaxNode> ancestors)
{
_variables.Clear();
_field.Clear();
_type.Clear();
_action.Clear();
_touchedFragments.Clear();
ObjectType type = _schema.GetOperationType(node.Operation);
_type.Push(type);
for (var i = 0; i < node.VariableDefinitions.Count; i++)
{
_declared.Add(
node.VariableDefinitions[i].Variable.Name.Value);
}
return VisitorAction.Continue;
}
19
Source : WorkScheduler.Pooling.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public void Clear()
{
lock (_sync)
{
TryContinue();
if (_batchDispatcher is not null)
{
_batchDispatcher.TaskEnqueued -= BatchDispatcherEventHandler;
_batchDispatcher = default!;
}
_work.Clear();
_suspended.Clear();
_stateMachine.Clear();
_deferredWorkBacklog.Clear();
_selections.Clear();
_processing = false;
_completed = false;
_requestContext = default!;
_errorHandler = default!;
_result = default!;
_diagnosticEvents = default!;
_requestAborted = default;
_isInitialized = false;
}
}
19
Source : WorkScheduler.Pooling.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public void ResetStateMachine()
{
lock (_sync)
{
TryContinue();
_work.Clear();
_serial.Clear();
_suspended.Clear();
_stateMachine.Clear();
_selections.Clear();
_stateMachine.Initialize(this, _operationContext.QueryPlan);
_processing = false;
_completed = false;
}
}
19
Source : TypeInitializer.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
private IEnumerable<RegisteredType> GetNextBatch(
ISet<ITypeReference> processed)
{
foreach (RegisteredType type in _next)
{
if (TryNormalizeDependencies(type.Conditionals, out IReadOnlyList<ITypeReference>? normalized) &&
processed.IsSupersetOf(GetTypeRefsExceptSelfRefs(type, normalized)))
{
yield return type;
}
else
{
_temp.Add(type);
}
}
_next.Clear();
if (_temp.Count > 0)
{
_next.AddRange(_temp);
_temp.Clear();
}
List<ITypeReference> GetTypeRefsExceptSelfRefs(
RegisteredType type,
IReadOnlyList<ITypeReference> normalizedTypeReferences)
{
_typeRefs.Clear();
_typeRefSet.Clear();
_typeRefSet.UnionWith(type.References);
foreach (ITypeReference? typeRef in normalizedTypeReferences)
{
if (_typeRefSet.Add(typeRef))
{
_typeRefs.Add(typeRef);
}
}
return _typeRefs;
}
}
19
Source : InterfaceCompletionTypeInterceptor.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public override void OnTypesInitialized(
IReadOnlyCollection<ITypeDiscoveryContext> discoveryContexts)
{
// after all types have been initialized we will index the runtime
// types of all interfaces.
foreach (TypeInfo interfaceTypeInfo in _typeInfos.Values
.Where(t => t.Definition.RuntimeType is { } rt &&
rt != typeof(object) &&
t.Definition is InterfaceTypeDefinition))
{
_allInterfaceRuntimeTypes.Add(interfaceTypeInfo.Definition.RuntimeType);
}
// we now will use the runtime types to infer interface usage ...
foreach (TypeInfo typeInfo in _typeInfos.Values.Where(IsRelevant))
{
_interfaceRuntimeTypes.Clear();
TryInferInterfaceFromRuntimeType(
GetRuntimeType(typeInfo),
_allInterfaceRuntimeTypes,
_interfaceRuntimeTypes);
if (_interfaceRuntimeTypes.Count > 0)
{
// if we detect that this type implements an interface,
// we will register it as a dependency.
foreach (TypeDependency? typeDependency in _interfaceRuntimeTypes.Select(
t => new TypeDependency(
TypeReference.Create(
typeInfo.Context.TypeInspector.GetType(t),
TypeContext.Output),
TypeDependencyKind.Completed)))
{
typeInfo.Context.Dependencies.Add(typeDependency);
typeInfo.Definition.Interfaces.Add(typeDependency.TypeReference);
}
}
}
}
19
Source : InterfaceCompletionTypeInterceptor.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public override void OnBeforeCompleteType(
ITypeCompletionContext completionContext,
DefinitionBase? definition,
IDictionary<string, object?> contextData)
{
if (definition is InterfaceTypeDefinition { Interfaces: { Count: > 0 } } typeDef)
{
_completed.Clear();
_completedFields.Clear();
_backlog.Clear();
foreach (ITypeReference? interfaceRef in typeDef.Interfaces)
{
if (completionContext.TryGetType(
interfaceRef,
out InterfaceType? interfaceType))
{
_completed.Add(interfaceType.Name);
_backlog.Enqueue(interfaceType);
}
}
foreach (InterfaceFieldDefinition? field in typeDef.Fields)
{
_completedFields.Add(field.Name);
}
CompleteInterfacesAndFields(typeDef);
}
if (definition is ObjectTypeDefinition { Interfaces: { Count: > 0 } } objectTypeDef)
{
_completed.Clear();
_completedFields.Clear();
_backlog.Clear();
foreach (ITypeReference? interfaceRef in objectTypeDef.Interfaces)
{
if (completionContext.TryGetType(
interfaceRef,
out InterfaceType? interfaceType))
{
_completed.Add(interfaceType.Name);
_backlog.Enqueue(interfaceType);
}
}
foreach (ObjectFieldDefinition? field in objectTypeDef.Fields)
{
_completedFields.Add(field.Name);
}
CompleteInterfacesAndFields(objectTypeDef);
}
}
19
Source : MergeRequestHelper.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public static void DispatchResults(
IQueryResult mergedResult,
IEnumerable<BufferedRequest> requests)
{
try
{
var handledErrors = new HashSet<IError>();
BufferedRequest? current = null;
QueryResultBuilder? resultBuilder = null;
foreach (BufferedRequest request in requests)
{
if (current is not null && resultBuilder is not null)
{
current.Promise.SetResult(resultBuilder.Create());
}
try
{
current = request;
resultBuilder = ExtractResult(request.Aliases!, mergedResult, handledErrors);
}
catch (Exception ex)
{
current = null;
resultBuilder = null;
request.Promise.SetException(ex);
}
}
if (current is not null && resultBuilder is not null)
{
if (mergedResult.Errors is not null &&
handledErrors.Count < mergedResult.Errors.Count)
{
foreach (IError error in mergedResult.Errors.Except(handledErrors))
{
resultBuilder.AddError(error);
}
}
handledErrors.Clear();
current.Promise.SetResult(resultBuilder.Create());
}
}
catch (Exception ex)
{
foreach (BufferedRequest request in requests)
{
request.Promise.TrySetException(ex);
}
}
}
19
Source : ExtractOperationContext.cs
with MIT License
from ChilliCream
with MIT License
from ChilliCream
public bool Next()
{
ExportedFragments.Clear();
VisitedFragments.Clear();
return SelectNext();
}
19
Source : ManagedMqttClient.cs
with MIT License
from chkr1011
with MIT License
from chkr1011
async Task PublishSubscriptionsAsync(TimeSpan timeout, CancellationToken cancellationToken)
{
var endTime = DateTime.UtcNow + timeout;
while (await _subscriptionsQueuedSignal.WaitAsync(GetRemainingTime(endTime), cancellationToken).ConfigureAwait(false))
{
List<MqttTopicFilter> subscriptions;
HashSet<string> unsubscriptions;
lock (_subscriptions)
{
subscriptions = _subscriptions.Select(i => new MqttTopicFilter
{
Topic = i.Key,
QualityOfServiceLevel = i.Value
}).ToList();
_subscriptions.Clear();
unsubscriptions = new HashSet<string>(_unsubscriptions);
_unsubscriptions.Clear();
}
if (!subscriptions.Any() && !unsubscriptions.Any())
{
continue;
}
_logger.Verbose("Publishing {0} added and {1} removed subscriptions", subscriptions.Count, unsubscriptions.Count);
foreach (var unsubscription in unsubscriptions)
{
_reconnectSubscriptions.Remove(unsubscription);
}
foreach (var subscription in subscriptions)
{
_reconnectSubscriptions[subscription.Topic] = subscription.QualityOfServiceLevel;
}
var addedTopicFilters = new List<MqttTopicFilter>();
foreach (var subscription in subscriptions)
{
addedTopicFilters.Add(subscription);
if (addedTopicFilters.Count == Options.MaxTopicFiltersInSubscribeUnsubscribePackets)
{
await SendSubscribeUnsubscribe(addedTopicFilters, null).ConfigureAwait(false);
addedTopicFilters.Clear();
}
}
await SendSubscribeUnsubscribe(addedTopicFilters, null).ConfigureAwait(false);
var removedTopicFilters = new List<string>();
foreach (var unSub in unsubscriptions)
{
removedTopicFilters.Add(unSub);
if (removedTopicFilters.Count == Options.MaxTopicFiltersInSubscribeUnsubscribePackets)
{
await SendSubscribeUnsubscribe(null, removedTopicFilters).ConfigureAwait(false);
removedTopicFilters.Clear();
}
}
await SendSubscribeUnsubscribe(null, removedTopicFilters).ConfigureAwait(false);
}
}
19
Source : ManagedMqttClient.cs
with MIT License
from chkr1011
with MIT License
from chkr1011
async Task MaintainConnectionAsync(CancellationToken cancellationToken)
{
try
{
while (!cancellationToken.IsCancellationRequested)
{
await TryMaintainConnectionAsync(cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
}
catch (Exception exception)
{
_logger.Error(exception, "Error exception while maintaining connection.");
}
finally
{
if (!IsDisposed)
{
try
{
using (var disconnectTimeout = new CancellationTokenSource(Options.ClientOptions.CommunicationTimeout))
{
await InternalClient.DisconnectAsync(disconnectTimeout.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
_logger.Warning("Timeout while sending DISCONNECT packet.");
}
catch (Exception exception)
{
_logger.Error(exception, "Error while disconnecting.");
}
_logger.Info("Stopped");
}
_reconnectSubscriptions.Clear();
lock (_subscriptions)
{
_subscriptions.Clear();
_unsubscriptions.Clear();
}
}
}
19
Source : DeadEndTrimmer.cs
with MIT License
from Chris3606
with MIT License
from Chris3606
public static void Trim(ISettableMapView<bool> map, IEnumerable<MapArea> areas, int saveDeadEndChance = 100, int maxTrimIterations = -1, IGenerator rng = null)
{
if (rng == null)
rng = SingletonRandom.DefaultRNG;
foreach (var area in areas)
{
HashSet<Coord> safeDeadEnds = new HashSet<Coord>();
HashSet<Coord> deadEnds = new HashSet<Coord>();
int iteration = 1;
while (maxTrimIterations == -1 || iteration <= maxTrimIterations)
{
foreach (var point in area.Positions)
{
var points = AdjacencyRule.EIGHT_WAY.NeighborsClockwise(point).ToArray();
var directions = AdjacencyRule.EIGHT_WAY.DirectionsOfNeighborsClockwise(Direction.NONE).ToList();
for (int i = 0; i < 8; i += 2)
{
if (map[points[i]])
{
var oppDir = directions[i] + 4;
bool found = false;
// If we get here, source direction is a floor, opposite direction
// should be wall
if (!map[points[(int)oppDir.Type]])
{
switch (oppDir.Type)
{
// Check for a wall pattern in the map. In this case
// something like where X is a wall XXX X X
case Direction.Types.UP:
found = !map[points[(int)Direction.Types.UP_LEFT]] &&
!map[points[(int)Direction.Types.UP_RIGHT]] &&
!map[points[(int)Direction.Types.LEFT]] &&
!map[points[(int)Direction.Types.RIGHT]];
break;
case Direction.Types.DOWN:
found = !map[points[(int)Direction.Types.DOWN_LEFT]] &&
!map[points[(int)Direction.Types.DOWN_RIGHT]] &&
!map[points[(int)Direction.Types.LEFT]] &&
!map[points[(int)Direction.Types.RIGHT]];
break;
case Direction.Types.RIGHT:
found = !map[points[(int)Direction.Types.UP_RIGHT]] &&
!map[points[(int)Direction.Types.DOWN_RIGHT]] &&
!map[points[(int)Direction.Types.UP]] &&
!map[points[(int)Direction.Types.DOWN]];
break;
case Direction.Types.LEFT:
found = !map[points[(int)Direction.Types.UP_LEFT]] &&
!map[points[(int)Direction.Types.DOWN_LEFT]] &&
!map[points[(int)Direction.Types.UP]] &&
!map[points[(int)Direction.Types.DOWN]];
break;
}
}
if (found)
deadEnds.Add(point);
break;
}
}
}
deadEnds.ExceptWith(safeDeadEnds); // Remove safeDeadEnds from deadEnds
area.Remove(deadEnds); // Remove dead ends from positions
if (deadEnds.Count == 0)
break;
foreach (var point in deadEnds)
{
if (PercentageCheck(saveDeadEndChance, rng))
safeDeadEnds.Add(point);
else
map[point] = false;
}
deadEnds.Clear();
iteration++;
}
}
}
19
Source : NavAStar.cs
with MIT License
from chris-gong
with MIT License
from chris-gong
public void ClearPath() {
if (g_Fringe != null) g_Fringe.Clear();
if (g_OpenList != null) g_OpenList.Clear();
if (g_ClosedList != null) g_ClosedList.Clear();
}
See More Examples