Here are the examples of the csharp api System.Collections.Generic.HashSet.Add(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1034 Examples
19
View Source File : AvifFile.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private static replacedgeneousTileInfo GetreplacedgeneousTileInfo(Surface surface, Rectangle[] tileRects, bool includeAlphaTiles)
{
Dictionary<int, int> duplicateColorTileMap = new Dictionary<int, int>();
HashSet<int> replacedgeneousColorTiles = new HashSet<int>();
Dictionary<int, int> duplicateAlphaTileMap = new Dictionary<int, int>();
HashSet<int> replacedgeneousAlphaTiles = new HashSet<int>();
if (tileRects.Length > 1)
{
Dictionary<uint, int> replacedgeneousColorTileCache = new Dictionary<uint, int>();
Dictionary<byte, int> replacedgeneousAlphaTileCache = new Dictionary<byte, int>();
for (int i = 0; i < tileRects.Length; i++)
{
if (IsreplacedgeneousColorTile(surface, tileRects[i], out uint firstPixelBgr))
{
replacedgeneousColorTiles.Add(i);
if (replacedgeneousColorTileCache.TryGetValue(firstPixelBgr, out int duplicateTileIndex))
{
duplicateColorTileMap.Add(i, duplicateTileIndex);
}
else
{
replacedgeneousColorTileCache.Add(firstPixelBgr, i);
}
}
if (includeAlphaTiles)
{
if (IsreplacedgeneousAlphaTile(surface, tileRects[i], out byte firstPixelAlpha))
{
replacedgeneousAlphaTiles.Add(i);
if (replacedgeneousAlphaTileCache.TryGetValue(firstPixelAlpha, out int duplicateTileIndex))
{
duplicateAlphaTileMap.Add(i, duplicateTileIndex);
}
else
{
replacedgeneousAlphaTileCache.Add(firstPixelAlpha, i);
}
}
}
}
}
return new replacedgeneousTileInfo(duplicateColorTileMap,
replacedgeneousColorTiles,
duplicateAlphaTileMap,
replacedgeneousAlphaTiles);
}
19
View Source File : FuzzerShould.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
[Test]
public void Indicate_what_to_do_in_the_DuplicationException_message_when_using_NoDuplication_mode()
{
var fuzzer = new Fuzzer(noDuplication: true);
var set = new HashSet<int>();
for (var i = 0; i < 5; i++)
{
set.Add(fuzzer.GenerateInteger(1, 5));
}
Check.That(set).Contains(1, 2, 3, 4, 5);
// So far we have called 5 times fuzzer.GenerateInteger(1, 5)
// But since the fuzzer could find 5 different values, we are OK
Check.ThatCode(() =>
{
// But this will be the call one should not make ;-)
return fuzzer.GenerateInteger(1, 5);
})
.Throws<DuplicationException>()
.WithMessage(@$"Couldn't find a non-already provided value of System.Int32 after 100 attempts. Already provided values: 1, 2, 3, 4, 5. You can either:
- Generate a new specific fuzzer to ensure no duplication is provided for a sub-group of fuzzed values (anytime you want through the {nameof(IFuzz.GenerateNoDuplicationFuzzer)}() method of your current Fuzzer instance. E.g.: var tempFuzzer = fuzzer.{nameof(IFuzz.GenerateNoDuplicationFuzzer)}();)
- Increase the value of the {nameof(Fuzzer.MaxFailingAttemptsForNoDuplication)} property for your {nameof(IFuzz)} instance.");
}
19
View Source File : UdpClient.cs
License : MIT License
Project Creator : a11s
License : MIT License
Project Creator : a11s
public void Connect(IPEndPoint ipep, bool CreateBackgroundThread)
{
IOThreads.Clear();
lastHandshakeTime = DateTime.MinValue;
Incoming = new ConcurrentQueue<byte[]>();
Outgoing = new ConcurrentQueue<byte[]>();
udp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
bool bNewBehavior = false;
byte[] dwBytesReturned = new byte[4];
udp.IOControl((int)SIO_UDP_CONNRESET, BitConverter.GetBytes(bNewBehavior), dwBytesReturned);
}
defpb = new ServerPackBuilderEx(defpb.GetSysIdBuf(), SessionId);
remote_ipep = ipep;
udp.Connect(remote_ipep);
if (CreateBackgroundThread)
{
ioThread = new Thread(ioLoop);
ioThread.IsBackground = true;
ioThread.Name = $"{nameof(ioThread)}";
IOThreads.Add(ioThread.ManagedThreadId);
ioThread.Start();
}
debug?.Invoke($"start connect");
}
19
View Source File : GridAcademy.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public override void AcademyReset()
{
foreach (GameObject actor in actorObjs)
{
DestroyImmediate(actor);
}
SetEnvironment();
actorObjs = new List<GameObject>();
HashSet<int> numbers = new HashSet<int>();
while (numbers.Count < players.Length)
{
numbers.Add(Random.Range(0, (int)resetParameters["gridSize"] * (int)resetParameters["gridSize"]));
}
int[] numbersA = Enumerable.ToArray(numbers);
for (int i = 0; i < players.Length; i++)
{
int x = (numbersA[i]) / (int)resetParameters["gridSize"];
int y = (numbersA[i]) % (int)resetParameters["gridSize"];
GameObject actorObj = (GameObject)GameObject.Instantiate(Resources.Load(players[i]));
actorObj.transform.position = new Vector3(x, -0.25f, y);
actorObj.name = players[i];
actorObjs.Add(actorObj);
if (players[i] == "agent")
{
trueAgent.transform.position = actorObj.transform.position;
trueAgent.transform.rotation = actorObj.transform.rotation;
visualAgent = actorObj;
}
}
}
19
View Source File : AttackServer.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public AttackInitiatorFromSrv RequestInitiator(AttackInitiatorToSrv fromClient)
{
lock (SyncObj)
{
//первые 5 минут не проверяем на отключения, т.к. загрузка может быть долгой (а дисконектит уже после 10 сек)
if ((fromClient.State == 10 || (DateTime.UtcNow - CreateTime).TotalSeconds > 8 * 60)
&& CheckConnect(true))
{
return new AttackInitiatorFromSrv()
{
State = State
};
}
if (fromClient.State == 0 && fromClient.StartHostPlayer != null)
{
State = 1;
TestMode = fromClient.TestMode;
return new AttackInitiatorFromSrv()
{
State = State
};
}
if (fromClient.State == 1)
{
return new AttackInitiatorFromSrv()
{
State = State
};
}
if (fromClient.State == 2 && State >= 2 && fromClient.Pawns != null && fromClient.Pawns.Count > 0)
{
Pawns = fromClient.Pawns;
//После передачи своих пешек, в ответ передаются данные карты и начинается её длительное создание
//в это время включаем на хосте обязательную паузу
//После загрузки пауза обновлется на 1 минуту, чтобы атакующий огляделся (ищи SetPauseOnTimeToHost в GameAttacker)
SetPauseOnTimeToHost = DateTime.UtcNow.AddMinutes(8);
Loger.Log("Server Set 1 SetPauseOnTimeToHost=" + SetPauseOnTimeToHost.Value.ToGoodUtcString());
return new AttackInitiatorFromSrv()
{
State = State,
TestMode = TestMode,
};
}
if (fromClient.State == 3 && State >= 3)
{
return new AttackInitiatorFromSrv()
{
State = State,
MapSize = MapSize,
TerrainDefNameCell = TerrainDefNameCell,
TerrainDefName = TerrainDefName,
Thing = Thing,
ThingCell = ThingCell,
};
}
if (fromClient.State == 10 && State < 10)
{
return new AttackInitiatorFromSrv()
{
State = State,
};
}
if (fromClient.State == 10)
{
AttackUpdateTick++;
if (StartTime == DateTime.MinValue)
{
Loger.Log($"Server AttackServer {Attacker.Public.Login} -> {Host.Public.Login} Start");
StartTime = DateTime.UtcNow;
}
if (fromClient.VictoryHostToHost)
{
VictoryHostToHost = fromClient.VictoryHostToHost;
}
if (fromClient.TerribleFatalError)
{
Loger.Log($"Server AttackServer TerribleFatalError {AttackUpdateTick}");
if (AttackUpdateTick != 2)
{
//такая ошибка с отменой атаки возможна только на 2 обновлении (на 1 создаются все пешки, на 2 проверка, что все переданы)
//если это не 2, то считаем, что атакующий жульничает
VictoryHostToHost = true;
}
else
{
TerribleFatalError = fromClient.TerribleFatalError;
SendAttackCancel();
Finish();
}
}
if (fromClient.SetPauseOnTimeToHost != TimeSpan.MinValue)
{
SetPauseOnTimeToHost = DateTime.UtcNow + fromClient.SetPauseOnTimeToHost;
Loger.Log("Server Set 2 SetPauseOnTimeToHost=" + SetPauseOnTimeToHost.Value.ToGoodUtcString());
}
if (fromClient.UpdateCommand != null && fromClient.UpdateCommand.Count > 0)
{
//объединяем
for (int i = 0; i < fromClient.UpdateCommand.Count; i++)
{
var id = fromClient.UpdateCommand[i].HostPawnID;
UpdateCommand[id] = fromClient.UpdateCommand[i];
}
}
if (fromClient.NeedNewThingIDs != null && fromClient.NeedNewThingIDs.Count > 0)
{
//объединяем
for (int i = 0; i < fromClient.NeedNewThingIDs.Count; i++)
{
NeedNewThingIDs.Add(fromClient.NeedNewThingIDs[i]);
}
}
var res = new AttackInitiatorFromSrv()
{
State = State,
NewPawns = NewPawns,
NewPawnsId = NewPawnsId,
NewThings = NewThings,
NewThingsId = NewThingsId,
NewCorpses = NewCorpses,
Delete = Delete,
UpdateState = UpdateState.Values.ToList(),
Finishing = VictoryAttacker != null,
VictoryAttacker = VictoryAttacker != null ? VictoryAttacker.Value : false,
};
NewPawns = new List<ThingEntry>();
NewPawnsId = new List<int>();
NewThings = new List<ThingTrade>();
NewThingsId = new List<int>();
NewCorpses = new List<AttackCorpse>();
Delete = new List<int>();
UpdateState = new Dictionary<int, AttackThingState>();
if (VictoryAttacker != null) Finish();
return res;
}
return new AttackInitiatorFromSrv()
{
ErrorText = "Unexpected request " + fromClient.State.ToString() + "! Was expected" + State.ToString()
};
}
}
19
View Source File : SplineDataProviderInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
protected override void OnSceneGUI()
{
base.OnSceneGUI();
// We skip the first point as it should always remain at the GameObject's local origin (Pose.ZeroIdenreplacedy)
for (int i = 1; i < controlPoints?.arraySize; i++)
{
bool isTangentHandle = i % 3 != 0;
serializedObject.Update();
bool isLastPoint = i == controlPoints.arraySize - 1;
var controlPointPosition = LineData.GetPoint(i);
var controlPointProperty = controlPoints.GetArrayElementAtIndex(i);
var controlPointRotation = controlPointProperty.FindPropertyRelative("rotation");
// Draw our tangent lines
Handles.color = Color.gray;
if (i == 1)
{
Handles.DrawLine(LineData.GetPoint(0), LineData.GetPoint(1));
}
else if (!isTangentHandle)
{
Handles.DrawLine(LineData.GetPoint(i), LineData.GetPoint(i - 1));
if (!isLastPoint)
{
Handles.DrawLine(LineData.GetPoint(i), LineData.GetPoint(i + 1));
}
}
Handles.color = isTangentHandle ? Color.white : Color.green;
float handleSize = HandleUtility.GetHandleSize(controlPointPosition);
if (Handles.Button(controlPointPosition, controlPointRotation.quaternionValue, handleSize * HandleSizeModifier, handleSize * PickSizeModifier, Handles.DotHandleCap))
{
selectedHandleIndex = i;
}
// Draw our handles
if (Tools.current == Tool.Move && selectedHandleIndex == i)
{
EditorGUI.BeginChangeCheck();
var newTargetPosition = Handles.PositionHandle(controlPointPosition, controlPointRotation.quaternionValue);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(LineData, "Change Spline Point Position");
LineData.SetPoint(i, newTargetPosition);
}
if (isLastPoint)
{
DrawSceneControlOptionButtons(controlPointPosition);
}
}
else if (Tools.current == Tool.Rotate && selectedHandleIndex == i)
{
EditorGUI.BeginChangeCheck();
Quaternion newTargetRotation = Handles.RotationHandle(controlPointRotation.quaternionValue, controlPointPosition);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(LineData, "Change Spline Point Rotation");
controlPointRotation.quaternionValue = newTargetRotation;
}
}
serializedObject.ApplyModifiedProperties();
}
// Check for overlapping points
OverlappingPointIndexes.Clear();
for (int i = 0; i < splineData.ControlPoints.Length; i++)
{
for (int j = 0; j < splineData.ControlPoints.Length; j++)
{
if (i == j)
{
continue;
}
if (Vector3.Distance(splineData.ControlPoints[i].Position, splineData.ControlPoints[j].Position) < OverlappingPointThreshold)
{
if (i != 0)
{
OverlappingPointIndexes.Add(i);
}
if (j != 0)
{
OverlappingPointIndexes.Add(j);
}
break;
}
}
}
}
19
View Source File : UIMaterialInstantiator.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void TryCreateMaterialCopy(Graphic targetGraphic)
{
int targetId = targetGraphic.GetInstanceID();
if (!targetInstances.Contains(targetId))
{
targetInstances.Add(targetId);
targetGraphic.material = new Material(targetGraphic.material);
}
}
19
View Source File : KeyBinding.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void PressKey(KeyBinding kb)
{
if (kb.TryGetMouseButton(out int mouseButton))
{
SimulatedMouseDownSet.Add(mouseButton);
SimulatedMouseSet.Add(mouseButton);
SimulatedMouseUpSet.Remove(mouseButton);
}
if (kb.TryGetKeyCode(out KeyCode keyCode))
{
SimulatedKeyDownSet.Add(keyCode);
SimulatedKeySet.Add(keyCode);
SimulatedKeyUpSet.Remove(keyCode);
}
}
19
View Source File : KeyBinding.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void ReleaseKey(KeyBinding kb)
{
if (kb.TryGetMouseButton(out int mouseButton))
{
SimulatedMouseDownSet.Remove(mouseButton);
SimulatedMouseSet.Remove(mouseButton);
SimulatedMouseUpSet.Add(mouseButton);
}
if (kb.TryGetKeyCode(out KeyCode keyCode))
{
SimulatedKeyDownSet.Remove(keyCode);
SimulatedKeySet.Remove(keyCode);
SimulatedKeyUpSet.Add(keyCode);
}
}
19
View Source File : TextFormattingConverterBase.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public string HighlightTermsBase(string text, string[] terms)
{
var set = new HashSet<int>();
foreach (var term in terms)
{
var indexes = text.ToLower().AllIndexesOf(term).Reverse().ToList();
foreach (var index in indexes)
{
for (int j = 0; j < term.Length; j++)
{
set.Add(j + index);
}
}
}
if (set.Count > 0)
{
var list = set.ToList();
list.Sort();
var ranges = GetRanges(list.ToArray());
ranges.Reverse();
var color = HighlightColor ?? Colors.Black;
string colorString = string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", color.A, color.R, color.G, color.B);
foreach (var range in ranges)
{
text = text.Insert(range.Item1 + range.Item2, "</Run>");
text = text.Insert(range.Item1, string.Format("<Run Foreground=\"{0}\">", colorString));
}
}
return text;
}
19
View Source File : TabControlHelper.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
private static void ModifyTabControl(Selector tabControl)
{
tabControl.SelectionChanged += OnSelectionChangedForSwitchAnimation;
tabControl.Loaded += OnLoadedForSwitchAnimation;
_initializedTabControlSet.Add(tabControl.GetHashCode());
}
19
View Source File : KeyboardHookManager.cs
License : MIT License
Project Creator : adainrivers
License : MIT License
Project Creator : adainrivers
private async Task HandleSingleKeyboardInput(object keyboardParamsObj)
{
var keyboardParams = (KeyboardParams)keyboardParamsObj;
var wParam = keyboardParams.wParam;
var vkCode = keyboardParams.vkCode;
var modifierKey = ModifierKeysUtilities.GetModifierKeyFromCode(vkCode);
// If the keyboard event is a KeyDown event (i.e. key pressed)
if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
{
// In this case, we only care about modifier keys
if (modifierKey != null)
{
lock (_modifiersLock)
{
_downModifierKeys.Add(modifierKey.Value);
}
}
// Trigger callbacks that are registered for this key, but only once per key press
if (!_downKeys.Contains(vkCode))
{
_downKeys.Add(vkCode);
}
}
// If the keyboard event is a KeyUp event (i.e. key released)
if (wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP)
{
await HandleKeyPress(vkCode);
// If the released key is a modifier key, remove it from the HashSet of modifier keys
if (modifierKey != null)
{
lock (_modifiersLock)
{
_downModifierKeys.Remove(modifierKey.Value);
}
}
_downKeys.Remove(vkCode);
}
}
19
View Source File : TriangleMeshConvexContactManifold.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
bool replacedyzeCandidate(ref TriangleIndices indices, TrianglePairTester pairTester, ref ContactData contact)
{
switch (pairTester.GetRegion(ref contact))
{
case VoronoiRegion.A:
//Add the contact.
VertexContact vertexContact;
GetNormal(ref contact.Normal, out vertexContact.CorrectedNormal);
vertexContact.ContactData = contact;
vertexContact.Vertex = indices.A;
vertexContact.ShouldCorrect = pairTester.ShouldCorrectContactNormal;
vertexContacts.Add(ref vertexContact);
//Block all of the other voronoi regions.
blockedEdgeRegions.Add(new Edge(indices.A, indices.B));
blockedEdgeRegions.Add(new Edge(indices.B, indices.C));
blockedEdgeRegions.Add(new Edge(indices.A, indices.C));
blockedVertexRegions.Add(indices.B);
blockedVertexRegions.Add(indices.C);
break;
case VoronoiRegion.B:
//Add the contact.
GetNormal(ref contact.Normal, out vertexContact.CorrectedNormal);
vertexContact.ContactData = contact;
vertexContact.Vertex = indices.B;
vertexContact.ShouldCorrect = pairTester.ShouldCorrectContactNormal;
vertexContacts.Add(ref vertexContact);
//Block all of the other voronoi regions.
blockedEdgeRegions.Add(new Edge(indices.A, indices.B));
blockedEdgeRegions.Add(new Edge(indices.B, indices.C));
blockedEdgeRegions.Add(new Edge(indices.A, indices.C));
blockedVertexRegions.Add(indices.A);
blockedVertexRegions.Add(indices.C);
break;
case VoronoiRegion.C:
//Add the contact.
GetNormal(ref contact.Normal, out vertexContact.CorrectedNormal);
vertexContact.ContactData = contact;
vertexContact.Vertex = indices.C;
vertexContact.ShouldCorrect = pairTester.ShouldCorrectContactNormal;
vertexContacts.Add(ref vertexContact);
//Block all of the other voronoi regions.
blockedEdgeRegions.Add(new Edge(indices.A, indices.B));
blockedEdgeRegions.Add(new Edge(indices.B, indices.C));
blockedEdgeRegions.Add(new Edge(indices.A, indices.C));
blockedVertexRegions.Add(indices.A);
blockedVertexRegions.Add(indices.B);
break;
case VoronoiRegion.AB:
//Add the contact.
EdgeContact edgeContact;
GetNormal(ref contact.Normal, out edgeContact.CorrectedNormal);
edgeContact.Edge = new Edge(indices.A, indices.B);
edgeContact.ContactData = contact;
edgeContact.ShouldCorrect = pairTester.ShouldCorrectContactNormal;
edgeContacts.Add(ref edgeContact);
//Block all of the other voronoi regions.
blockedEdgeRegions.Add(new Edge(indices.B, indices.C));
blockedEdgeRegions.Add(new Edge(indices.A, indices.C));
blockedVertexRegions.Add(indices.A);
blockedVertexRegions.Add(indices.B);
blockedVertexRegions.Add(indices.C);
break;
case VoronoiRegion.AC:
//Add the contact.
GetNormal(ref contact.Normal, out edgeContact.CorrectedNormal);
edgeContact.Edge = new Edge(indices.A, indices.C);
edgeContact.ContactData = contact;
edgeContact.ShouldCorrect = pairTester.ShouldCorrectContactNormal;
edgeContacts.Add(ref edgeContact);
//Block all of the other voronoi regions.
blockedEdgeRegions.Add(new Edge(indices.A, indices.B));
blockedEdgeRegions.Add(new Edge(indices.B, indices.C));
blockedVertexRegions.Add(indices.A);
blockedVertexRegions.Add(indices.B);
blockedVertexRegions.Add(indices.C);
break;
case VoronoiRegion.BC:
//Add the contact.
GetNormal(ref contact.Normal, out edgeContact.CorrectedNormal);
edgeContact.Edge = new Edge(indices.B, indices.C);
edgeContact.ContactData = contact;
edgeContact.ShouldCorrect = pairTester.ShouldCorrectContactNormal;
edgeContacts.Add(ref edgeContact);
//Block all of the other voronoi regions.
blockedEdgeRegions.Add(new Edge(indices.A, indices.B));
blockedEdgeRegions.Add(new Edge(indices.A, indices.C));
blockedVertexRegions.Add(indices.A);
blockedVertexRegions.Add(indices.B);
blockedVertexRegions.Add(indices.C);
break;
default:
//Block all of the other voronoi regions.
blockedEdgeRegions.Add(new Edge(indices.A, indices.B));
blockedEdgeRegions.Add(new Edge(indices.B, indices.C));
blockedEdgeRegions.Add(new Edge(indices.A, indices.C));
blockedVertexRegions.Add(indices.A);
blockedVertexRegions.Add(indices.B);
blockedVertexRegions.Add(indices.C);
//Should add the contact.
return true;
}
return false;
}
19
View Source File : Planet.ChunkMeshHelpers.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
public HashSet<int> GetChunkMeshIndiciesEdge()
{
if (chunkMeshIndiciesEdge != null) return chunkMeshIndiciesEdge;
chunkMeshIndiciesEdge = new HashSet<int>();
int verticesOnEdge = chunkConfig.numberOfVerticesOnEdge;
for (int i = 0; i < verticesOnEdge; i++)
{
chunkMeshIndiciesEdge.Add(i); // top ling
chunkMeshIndiciesEdge.Add(verticesOnEdge * (verticesOnEdge - 1) + i); // bottom line
}
for (int i = 1; i < verticesOnEdge - 1; i++)
{
chunkMeshIndiciesEdge.Add(verticesOnEdge * i); // left line
chunkMeshIndiciesEdge.Add(verticesOnEdge * i + verticesOnEdge - 1); // right line
}
return chunkMeshIndiciesEdge;
}
19
View Source File : AtomicQueues.cs
License : MIT License
Project Creator : aksyr
License : MIT License
Project Creator : aksyr
[Test]
[TestCase(AllocationMode.Ephemeral)]
[TestCase(AllocationMode.Pooled)]
public void PreservesItems_WithSimultaneousQueueDequeue(AllocationMode allocationMode)
{
using (var queue = AtomicQueue<int>.Create(allocationMode))
{
var count = 0;
var allItems = new HashSet<int>();
var foundItems = new HashSet<int>();
var threads = new List<Thread>();
for (int i = 0; i < kWorkerCount; ++i)
{
allItems.Add(i + 1);
var thread = new Thread((o) =>
{
try
{
var item = Interlocked.Increment(ref count);
queue.Enqueue((int*)item);
}
catch (Exception e)
{
Debug.LogException(e);
}
});
thread.Start();
threads.Add(thread);
if (queue.TryDequeue(out var result))
foundItems.Add((int) result);
}
foreach (var thread in threads)
thread.Join();
while (foundItems.Count < kWorkerCount)
{
if (queue.TryDequeue(out var item))
foundItems.Add((int) item);
else
{
replacedert.Fail($"After adding was completed, queue was empty after popping only {foundItems.Count} items");
return;
}
}
replacedert.That(queue.IsEmpty);
Collectionreplacedert.AreEquivalent(allItems, foundItems);
}
}
19
View Source File : AtomicQueues.cs
License : MIT License
Project Creator : aksyr
License : MIT License
Project Creator : aksyr
[Test]
[TestCase(AllocationMode.Ephemeral)]
[TestCase(AllocationMode.Pooled)]
public void PreservesItems(AllocationMode allocationMode)
{
using (var queue = AtomicQueue<int>.Create(allocationMode))
{
var count = 0;
var items = new HashSet<int>();
var threads = new List<Thread>();
for (int i = 0; i < kWorkerCount; ++i)
{
var thread = new Thread((o) =>
{
var item = Interlocked.Increment(ref count);
queue.Enqueue((int*)item);
});
items.Add(i + 1);
thread.Start();
threads.Add(thread);
}
foreach (var thread in threads)
thread.Join();
replacedert.That(!queue.IsEmpty);
for (int i = 0; i < kWorkerCount; ++i)
{
var item = (int)queue.Dequeue();
replacedert.That(items.Contains(item), $"Missing item {item} (iteration {i})");
items.Remove(item);
}
replacedert.That(queue.IsEmpty);
replacedert.That(items.Count == 0);
}
}
19
View Source File : Fixture.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
public Fixture CloneOnto(Body body)
{
Fixture fixture = new Fixture();
fixture.Body = body;
fixture.Shape = Shape.Clone();
fixture.UserData = UserData;
fixture.Resreplacedution = Resreplacedution;
fixture.Friction = Friction;
fixture.IsSensor = IsSensor;
fixture._collisionGroup = _collisionGroup;
fixture._collisionCategories = _collisionCategories;
fixture._collidesWith = _collidesWith;
fixture.IgnoreCCDWith = IgnoreCCDWith;
foreach (int ignore in _collisionIgnores)
{
fixture._collisionIgnores.Add(ignore);
}
fixture.RegisterFixture();
return fixture;
}
19
View Source File : TagSystem.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
public bool AddTagToEntIdx(EntIdx e, Tag t)
{
return tags_[TagToArrIdx(t)].Add(e);
}
19
View Source File : Fixture.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
public void IgnoreCollisionWith(Fixture fixture)
{
if (!_collisionIgnores.Contains(fixture.FixtureId))
{
_collisionIgnores.Add(fixture.FixtureId);
Refilter();
}
}
19
View Source File : Connections.cs
License : MIT License
Project Creator : alerdenisov
License : MIT License
Project Creator : alerdenisov
public bool Add(int connection)
{
if(connections.Add(connection))
{
newConnection.OnNext(connection);
return true;
}
return false;
}
19
View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna
License : MIT License
Project Creator : alexanderdna
public void StoreReceivedBlocks(Block block)
{
if (storedBlockIndices.Contains(block.Index))
return;
storedBlockIndices.Add(block.Index);
storedBlocks.Add(block);
}
19
View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna
License : MIT License
Project Creator : alexanderdna
public void StoreReceivedBlocks(IList<Block> blocks)
{
for (int i = 0, c = blocks.Count; i < c; ++i)
{
var block = blocks[i];
if (storedBlockIndices.Contains(block.Index))
continue;
storedBlockIndices.Add(block.Index);
storedBlocks.Add(block);
}
}
19
View Source File : _217_ContainsDuplicate.cs
License : MIT License
Project Creator : AlexChesser
License : MIT License
Project Creator : AlexChesser
public bool ContainsDuplicate(int[] nums)
{
HashSet<int> dupeCheck = new HashSet<int>();
for (int i = 0; i < nums.Length; i++)
{
if (dupeCheck.Contains(nums[i]))
{
return true;
}
dupeCheck.Add(nums[i]);
}
return false;
}
19
View Source File : CommandLineAnalyzer.cs
License : MIT License
Project Creator : AlexGhiondea
License : MIT License
Project Creator : AlexGhiondea
private static void ValidateArguments(List<Argument> args, SymbolreplacedysisContext context)
{
HashSet<string> namesOfAllArgs = new HashSet<string>();
HashSet<int> positionsOrRequiredArgs = new HashSet<int>();
int numberOfPositionalArgs = 0;
int indexOfCollectionArg = -1;
RequiredArgument collectionArg = null;
foreach (var item in args)
{
if (item is OptionalArgument)
{
OptionalArgument oag = item as OptionalArgument;
// Validate that the same name is not used across required and optional arguments.
if (namesOfAllArgs.Contains(oag.Name))
{
context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, oag.Symbol.Locations.First(), oag.Name));
}
namesOfAllArgs.Add(oag.Name);
}
else if (item is RequiredArgument)
{
RequiredArgument rag = item as RequiredArgument;
numberOfPositionalArgs++;
// Validate that the same position is not used twice
if (positionsOrRequiredArgs.Contains(rag.Position))
{
context.ReportDiagnostic(Diagnostic.Create(DuplicatePositionalArgumentPositionRule, rag.Symbol.Locations.First(), rag.Position));
}
// Validate that the same name is not used across required and optional arguments.
if (namesOfAllArgs.Contains(rag.Name))
{
context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, rag.Symbol.Locations.First(), rag.Name));
}
// is the required collection argument the last one AND do we only have one of them?
if (indexOfCollectionArg >= 0 && rag.Position > indexOfCollectionArg)
{
context.ReportDiagnostic(Diagnostic.Create(OnlyOneRequiredCollection, rag.Symbol.Locations.First(), collectionArg.Name, rag.Name));
}
// do we have a collection argument specified?
if (rag.IsCollection)
{
indexOfCollectionArg = rag.Position;
collectionArg = rag;
}
namesOfAllArgs.Add(rag.Name);
positionsOrRequiredArgs.Add(rag.Position);
}
}
int checkedPositions = 0;
//validate that the positional arguments are in a continuous sequence, starting at 0
for (checkedPositions = 0; checkedPositions < numberOfPositionalArgs; checkedPositions++)
{
if (!positionsOrRequiredArgs.Contains(checkedPositions))
{
// at this point, we could not find the required positional argument 'i'
// we should give the error at the type level.
context.ReportDiagnostic(Diagnostic.Create(RequiredPositionalArgumentNotFound, args.First().Symbol.ContainingType.Locations.First(), numberOfPositionalArgs, checkedPositions));
break;
}
}
// Ensure that the required collection argument (if present) is last.
if (indexOfCollectionArg >= 0 && indexOfCollectionArg != numberOfPositionalArgs - 1)
{
context.ReportDiagnostic(Diagnostic.Create(CollectionArgumentShouldBeLast, collectionArg.Symbol.Locations.First(), collectionArg.Name));
}
}
19
View Source File : PieceManager.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
DateTime checkoutTime;
int pieceIndex;
HashSet<int> checkoutsToRemove = new HashSet<int>();
Thread.CurrentThread.Name = "piece manager checker";
this.timer.Interval = TimeSpan.FromDays(1).TotalMilliseconds;
lock (this.locker)
{
foreach (var checkOut in this.checkouts)
{
pieceIndex = checkOut.Key;
checkoutTime = checkOut.Value;
if (DateTime.UtcNow - checkoutTime > this.checkoutTimeout)
{
checkoutsToRemove.Add(checkOut.Key);
}
}
foreach (var checkoutToRemove in checkoutsToRemove)
{
this.checkouts.Remove(checkoutToRemove);
// checkout timeout -> mark piece as missing, giving other peers a chance to download it
this.BitField[checkoutToRemove] = PieceStatus.Missing;
}
}
this.timer.Interval = this.timerTimeout.TotalMilliseconds;
}
19
View Source File : DynamicUnionResolver.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private static TypeInfo BuildType(Type type)
{
TypeInfo ti = type.GetTypeInfo();
// order by key(important for use jump-table of switch)
UnionAttribute[] unionAttrs = ti.GetCustomAttributes<UnionAttribute>().OrderBy(x => x.Key).ToArray();
if (unionAttrs.Length == 0)
{
return null;
}
if (!ti.IsInterface && !ti.IsAbstract)
{
throw new MessagePackDynamicUnionResolverException("Union can only be interface or abstract clreplaced. Type:" + type.Name);
}
var checker1 = new HashSet<int>();
var checker2 = new HashSet<Type>();
foreach (UnionAttribute item in unionAttrs)
{
if (!checker1.Add(item.Key))
{
throw new MessagePackDynamicUnionResolverException("Same union key has found. Type:" + type.Name + " Key:" + item.Key);
}
if (!checker2.Add(item.SubType))
{
throw new MessagePackDynamicUnionResolverException("Same union subType has found. Type:" + type.Name + " SubType: " + item.SubType);
}
}
Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type);
using (MonoProtection.EnterRefEmitLock())
{
TypeBuilder typeBuilder = Dynamicreplacedembly.Value.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + +Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });
FieldBuilder typeToKeyAndJumpMap = null; // Dictionary<RuntimeTypeHandle, KeyValuePair<int, int>>
FieldBuilder keyToJumpMap = null; // Dictionary<int, int>
// create map dictionary
{
ConstructorBuilder method = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
typeToKeyAndJumpMap = typeBuilder.DefineField("typeToKeyAndJumpMap", typeof(Dictionary<RuntimeTypeHandle, KeyValuePair<int, int>>), FieldAttributes.Private | FieldAttributes.InitOnly);
keyToJumpMap = typeBuilder.DefineField("keyToJumpMap", typeof(Dictionary<int, int>), FieldAttributes.Private | FieldAttributes.InitOnly);
ILGenerator il = method.GetILGenerator();
BuildConstructor(type, unionAttrs, method, typeToKeyAndJumpMap, keyToJumpMap, il);
}
{
MethodBuilder method = typeBuilder.DefineMethod(
"Serialize",
MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
null,
new Type[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) });
ILGenerator il = method.GetILGenerator();
BuildSerialize(type, unionAttrs, method, typeToKeyAndJumpMap, il);
}
{
MethodBuilder method = typeBuilder.DefineMethod(
"Deserialize",
MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
type,
new Type[] { refMessagePackReader, typeof(MessagePackSerializerOptions) });
ILGenerator il = method.GetILGenerator();
BuildDeserialize(type, unionAttrs, method, keyToJumpMap, il);
}
return typeBuilder.CreateTypeInfo();
}
}
19
View Source File : NumberSetAttributeValue.cs
License : MIT License
Project Creator : AllocZero
License : MIT License
Project Creator : AllocZero
public HashSet<int> ToIntSet()
{
var result = new HashSet<int>(_items.Count);
foreach (var item in _items)
result.Add(int.Parse(item, CultureInfo.InvariantCulture));
return result;
}
19
View Source File : NativeStringTest.cs
License : MIT License
Project Creator : ancientproject
License : MIT License
Project Creator : ancientproject
public void LoadTest(string[] data)
{
var hashMap = new HashSet<int>();
foreach (var s in data)
replacedert.True(hashMap.Add(NativeString.GetHashCode(s)));
}
19
View Source File : RemoveSurfaceVertices.cs
License : MIT License
Project Creator : anderm
License : MIT License
Project Creator : anderm
private IEnumerator RemoveSurfaceVerticesWithinBoundsRoutine()
{
List<MeshFilter> meshFilters = SpatialMappingManager.Instance.GetMeshFilters();
float start = Time.realtimeSinceStartup;
while (boundingObjectsQueue.Count > 0)
{
// Get the current boundingObject.
Bounds bounds = boundingObjectsQueue.Dequeue();
foreach (MeshFilter filter in meshFilters)
{
// Since this is amortized across frames, the filter can be destroyed by the time
// we get here.
if (filter == null)
{
continue;
}
Mesh mesh = filter.sharedMesh;
MeshRenderer meshRenderer = filter.GetComponent<MeshRenderer>();
// The mesh renderer bounds are in world space.
// If the mesh is null there is nothing to process
// If the renderer is null we can't get the renderer bounds
// If the renderer's bounds aren't contained inside of the current
// bounds from the bounds queue there is no reason to process
// If any of the above conditions are met, then we should go to the next meshfilter.
if (mesh == null || meshRenderer == null || !meshRenderer.bounds.Intersects(bounds))
{
// We don't need to do anything to this mesh, move to the next one.
continue;
}
// Remove vertices from any mesh that intersects with the bounds.
Vector3[] verts = mesh.vertices;
HashSet<int> vertsToRemove = new HashSet<int>();
// Find which mesh vertices are within the bounds.
for (int i = 0; i < verts.Length; ++i)
{
if (bounds.Contains(filter.transform.TransformPoint(verts[i])))
{
// These vertices are within bounds, so mark them for removal.
vertsToRemove.Add(i);
}
// If too much time has preplaceded, we need to return control to the main game loop.
if ((Time.realtimeSinceStartup - start) > FrameTime)
{
// Pause our work here, and continue finding vertices to remove on the next frame.
yield return null;
start = Time.realtimeSinceStartup;
}
}
if (vertsToRemove.Count == 0)
{
// We did not find any vertices to remove, so move to the next mesh.
continue;
}
// We found vertices to remove, so now we need to remove any triangles that reference these vertices.
int[] indices = mesh.GetTriangles(0);
List<int> updatedIndices = new List<int>();
for (int index = 0; index < indices.Length; index += 3)
{
// Each triangle utilizes three slots in the index buffer, check to see if any of the
// triangle indices contain a vertex that should be removed.
if (vertsToRemove.Contains(indices[index]) ||
vertsToRemove.Contains(indices[index + 1]) ||
vertsToRemove.Contains(indices[index + 2]))
{
// Do nothing, we don't want to save this triangle...
}
else
{
// Every vertex in this triangle is good, so let's save it.
updatedIndices.Add(indices[index]);
updatedIndices.Add(indices[index + 1]);
updatedIndices.Add(indices[index + 2]);
}
// If too much time has preplaceded, we need to return control to the main game loop.
if ((Time.realtimeSinceStartup - start) > FrameTime)
{
// Pause our work, and continue making additional planes on the next frame.
yield return null;
start = Time.realtimeSinceStartup;
}
}
if (indices.Length == updatedIndices.Count)
{
// None of the verts to remove were being referenced in the triangle list.
continue;
}
// Update mesh to use the new triangles.
mesh.SetTriangles(updatedIndices.ToArray(), 0);
mesh.RecalculateBounds();
yield return null;
start = Time.realtimeSinceStartup;
// Reset the mesh collider to fit the new mesh.
MeshCollider meshCollider = filter.gameObject.GetComponent<MeshCollider>();
if (meshCollider != null)
{
meshCollider.sharedMesh = null;
meshCollider.sharedMesh = mesh;
}
}
}
Debug.Log("Finished removing vertices.");
// We are done removing vertices, trigger an event.
EventHandler handler = RemoveVerticesComplete;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
removingVerts = false;
}
19
View Source File : songdatabase.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil
License : GNU Lesser General Public License v3.0
Project Creator : angturil
void UpdateSearchEntry(string key, int id,bool Add = true)
{
if (Add) hashcount++; else hashcount--;
if (Add)
MapDatabase.SearchDictionary.AddOrUpdate(key, (k) => { HashSet<int> va = new HashSet<int>(); va.Add(id); return va; }, (k, va) => { va.Add(id); return va; });
else
{
MapDatabase.SearchDictionary[key].Remove(id); // An empty keyword is fine, and actually uncommon
}
}
19
View Source File : MultiSearchMerger.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
private List<MergeBuilder> MergeStep(List<MergeBuilder> builders, List<MultiSearchResult> results, int currentIndex)
{
MultiSearchResult nextResult = results[currentIndex];
PriorityQueue<MergePair> pairHeap = new PriorityQueue<MergePair>();
List<MergeBuilder> ret = new List<MultiSearchMerger.MergeBuilder>();
if ((builders.Count == 0) || (nextResult.Count == 0))
{
return ret;
}
pairHeap.Add(new MergePair(0, 0, builders[0].Cost + nextResult.GetCost(0)));
HashSet<int> visited = new HashSet<int>();
while (ret.Count < maxCount && pairHeap.Count > 0)
{
MergePair top = pairHeap.Poll();
if (GetCostLowerBound(top.Cost, currentIndex) - baseCost > costSlack)
{
break;
}
int i = top.LeftIndex;
int j = top.RightIndex;
MergeBuilder nextBuilder = new MergeBuilder(results, builders[i].Indices);
nextBuilder.Add(j);
ret.Add(nextBuilder);
if (i + 1 < builders.Count)
{
MergePair newMergePair = new MergePair(i + 1, j, builders[i + 1].Cost + nextResult.GetCost(j));
int positionValue = GetPositionValue(i + 1, j);
if (!visited.Contains(positionValue))
{
pairHeap.Add(newMergePair);
visited.Add(positionValue);
}
}
if (j + 1 < nextResult.Count)
{
MergePair newMergePair = new MergePair(i, j + 1, builders[i].Cost + nextResult.GetCost(j + 1));
int positionValue = GetPositionValue(i, j + 1);
if (!visited.Contains(positionValue))
{
pairHeap.Add(newMergePair);
visited.Add(positionValue);
}
}
}
return ret;
}
19
View Source File : TestUtils.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
public static void replacedertEqualTokenFeatureLengths<T>(string text, TokenizerBase<T> tokenizer) where T : TokenBase
{
var tokens = tokenizer.Tokenize(text);
HashSet<int> lengths = new HashSet<int>();
foreach (TokenBase token in tokens)
{
lengths.Add(token.GetAllFeaturesArray().Length);
}
replacedert.AreEqual(1, lengths.Count);
}
19
View Source File : NavMeshExporter.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : AnotherEnd15
private static void InputTriangles(int[] indices, int[] areas)
{
Face face = null;
var faceIndices = new HashSet<int>();
for (int i = 0, n = areas.Length; i < n; i++)
{
var triangleIndexList = new int[3];
var triangleVertList = new Vert[3];
for (var j = 0; j < 3; j++)
{
triangleIndexList[j] = indices[i * 3 + j];
triangleVertList[j] = indexVertDict[triangleIndexList[j]];
}
var vert0 = triangleVertList[0];
var vert1 = triangleVertList[1];
var vert2 = triangleVertList[2];
if (vert0 == vert1 || vert1 == vert2 || vert2 == vert0)
{
continue;
}
var newFace = true;
var area = areas[i] >= 3? areas[i] - 2 : 0;
if (face != null && face.area == area)
{
for (var j = 0; j < 3; j++)
{
if (faceIndices.Contains(triangleIndexList[j]))
{
newFace = false;
break;
}
}
}
if (newFace)
{
if (face != null)
{
InitFace(face);
faceIndices.Clear();
}
face = new Face();
face.area = area;
}
double x1 = vert1.x - vert0.x;
double y1 = vert1.y - vert0.y;
double z1 = vert1.z - vert0.z;
double x2 = vert2.x - vert0.x;
double y2 = vert2.y - vert0.y;
double z2 = vert2.z - vert0.z;
double normalA = y1 * z2 - z1 * y2;
double normalB = z1 * x2 - x1 * z2;
double normalC = x1 * y2 - y1 * x2;
if (normalB < -0.000001 || 0.000001 < normalB)
{
var normalD = normalA + normalB + normalC;
if (normalD > face.normalD)
{
face.normalA = normalA;
face.normalB = normalB;
face.normalC = normalC;
face.normalD = normalD;
}
}
for (var j = 0; j < 3; j++)
{
if (!faceIndices.Contains(triangleIndexList[j]))
{
faceIndices.Add(triangleIndexList[j]);
face.verts.Add(triangleVertList[j]);
}
}
}
if (face != null)
{
InitFace(face);
}
foreach (var pair in pairList)
{
var firstFace = pair.firstEdgeFace;
var secondFace = pair.secondEdgeFace;
var firstDistance = GetDistance(firstFace.centerX - pair.centerX, firstFace.centerZ - pair.centerZ);
var secondDistance = GetDistance(secondFace.centerX - pair.centerX, secondFace.centerZ - pair.centerZ);
pair.distance = firstDistance + secondDistance;
}
}
19
View Source File : MeshSkin.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
unsafe private bool AddTriangleBones(int* indices)
{
/*
* First of all you need to check if all the triangle's bones can be added
* if the test preplaced then add the
*/
int boneCount = 0;
_tempBonesSet.Clear();
//First of all you need to check if all the triangle's bones can be added
for (int k = 0; k < 3; k++)
{
float* bones = GetVertexBones(indices[k]);
float* weights = GetVertexWeights(indices[k]);
for (int ibone = 0; ibone < 4; ibone++)
{
//check all the bones
int boneIdx = (int)bones[ibone];
if (weights[ibone] > 0 && _boneLookup[boneIdx] < 0 && !_tempBonesSet.Contains(boneIdx))
{
boneCount++;
//if the bones is valid and its not in the layer check if there is space for it
if (_layerBonesCount + boneCount > _maxPalleteEntries)
return false;
//add the bone to the layer
_tempBonesSet.Add(boneIdx);
}
}
}
return true;
}
19
View Source File : ShrinkingChallengeTests.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd
License : Apache License 2.0
Project Creator : AnthonyLloyd
[Fact(Skip="fails")]
public void No2_LargeUnionList()
{
Gen.Int.Array.Array
.Sample(aa =>
{
var hs = new HashSet<int>();
foreach (var a in aa)
{
foreach (var i in a) hs.Add(i);
if (hs.Count >= 5) return false;
}
return true;
});
}
19
View Source File : SlimCollectionsTests.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd
License : Apache License 2.0
Project Creator : AnthonyLloyd
[Fact]
public void SetSlim_Performance_Add()
{
Gen.Int.Array
.Faster(
a =>
{
var s = new SetSlim<int>();
foreach (var i in a) s.Add(i);
},
a =>
{
var s = new HashSet<int>();
foreach (var i in a) s.Add(i);
},
repeat: 100, raiseexception: false
).Output(writeLine);
}
19
View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
public int RemoveNotesByTag(
BackupFile backup,
int[]? tagIds,
bool removeUntaggedNotes,
bool removereplacedociatedUnderlining,
bool removereplacedociatedTags)
{
if (backup == null)
{
throw new ArgumentNullException(nameof(backup));
}
tagIds ??= Array.Empty<int>();
var tagIdsHash = tagIds.ToHashSet();
var tagMapIdsToRemove = new HashSet<int>();
var noteIdsToRemove = new HashSet<int>();
var candidateUserMarks = new HashSet<int>();
if (removeUntaggedNotes)
{
// notes without a tag
foreach (var i in GetNotesWithNoTag(backup))
{
noteIdsToRemove.Add(i);
}
}
foreach (var tagMap in backup.Database.TagMaps)
{
if (tagIdsHash.Contains(tagMap.TagId) && tagMap.NoteId != null && tagMap.NoteId > 0)
{
tagMapIdsToRemove.Add(tagMap.TagMapId);
noteIdsToRemove.Add(tagMap.NoteId.Value);
var note = backup.Database.FindNote(tagMap.NoteId.Value);
if (note?.UserMarkId != null)
{
candidateUserMarks.Add(note.UserMarkId.Value);
}
}
}
backup.Database.TagMaps.RemoveAll(x => tagMapIdsToRemove.Contains(x.TagMapId));
backup.Database.TagMaps.RemoveAll(x => noteIdsToRemove.Contains(x.NoteId ?? 0));
backup.Database.Notes.RemoveAll(x => noteIdsToRemove.Contains(x.NoteId));
if (removereplacedociatedUnderlining)
{
RemoveUnderlining(backup.Database, candidateUserMarks);
}
if (removereplacedociatedTags)
{
RemoveSelectedTags(backup.Database, tagIdsHash);
}
return noteIdsToRemove.Count;
}
19
View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
public int RemoveUnderliningByColour(BackupFile backup, int[]? colorIndexes, bool removereplacedociatedNotes)
{
if (backup == null)
{
throw new ArgumentNullException(nameof(backup));
}
colorIndexes ??= Array.Empty<int>();
var userMarkIdsToRemove = new HashSet<int>();
foreach (var mark in backup.Database.UserMarks)
{
if (colorIndexes.Contains(mark.ColorIndex))
{
userMarkIdsToRemove.Add(mark.UserMarkId);
}
}
return RemoveUnderlining(backup.Database, userMarkIdsToRemove, removereplacedociatedNotes);
}
19
View Source File : Cleaner.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
private HashSet<int> GetUserMarkIdsInUse()
{
var result = new HashSet<int>();
foreach (var userMark in _database.UserMarks)
{
result.Add(userMark.UserMarkId);
}
return result;
}
19
View Source File : Cleaner.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
private HashSet<int> GetLocationIdsInUse()
{
var result = new HashSet<int>();
foreach (var bookmark in _database.Bookmarks)
{
result.Add(bookmark.LocationId);
result.Add(bookmark.PublicationLocationId);
}
foreach (var note in _database.Notes)
{
if (note.LocationId != null)
{
result.Add(note.LocationId.Value);
}
}
foreach (var userMark in _database.UserMarks)
{
result.Add(userMark.LocationId);
}
foreach (var tagMap in _database.TagMaps)
{
if (tagMap.LocationId != null)
{
result.Add(tagMap.LocationId.Value);
}
}
foreach (var inputFld in _database.InputFields)
{
result.Add(inputFld.LocationId);
}
Log.Logger.Debug($"Found {result.Count} location Ids in use");
return result;
}
19
View Source File : Cleaner.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
private int CleanBlockRanges()
{
int removed = 0;
var ranges = _database.BlockRanges;
if (ranges.Any())
{
var userMarkIdsFound = new HashSet<int>();
var userMarkIds = GetUserMarkIdsInUse();
foreach (var range in Enumerable.Reverse(ranges))
{
if (!userMarkIds.Contains(range.UserMarkId))
{
Log.Logger.Debug($"Removing redundant range: {range.BlockRangeId}");
ranges.Remove(range);
++removed;
}
else
{
if (userMarkIdsFound.Contains(range.UserMarkId))
{
// don't know how to handle this situation - we are expecting
// a unique constraint on the UserMarkId column but have found
// occasional duplication!
Log.Logger.Debug($"Removing redundant range (duplicate UserMarkId): {range.BlockRangeId}");
ranges.Remove(range);
++removed;
}
else
{
userMarkIdsFound.Add(range.UserMarkId);
}
}
}
}
return removed;
}
19
View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
public int RemoveUnderliningByPubAndColor(
BackupFile backup,
int colorIndex,
bool anyColor,
string? publicationSymbol,
bool anyPublication,
bool removereplacedociatedNotes)
{
if (backup == null)
{
throw new ArgumentNullException(nameof(backup));
}
if (string.IsNullOrEmpty(publicationSymbol) && !anyPublication)
{
throw new ArgumentNullException(nameof(publicationSymbol));
}
var userMarkIdsToRemove = new HashSet<int>();
foreach (var mark in backup.Database.UserMarks)
{
if (ShouldRemoveUnderlining(mark, backup.Database, colorIndex, anyColor, publicationSymbol, anyPublication))
{
userMarkIdsToRemove.Add(mark.UserMarkId);
}
}
return RemoveUnderlining(backup.Database, userMarkIdsToRemove, removereplacedociatedNotes);
}
19
View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
public int RemoveUnderlining(Database database)
{
if (database == null)
{
throw new ArgumentNullException(nameof(database));
}
if (!database.Notes.Any())
{
var count = database.UserMarks.Count;
database.UserMarks.Clear();
return count;
}
// we must retain user marks that are replacedociated with notes...
HashSet<int> userMarksToRetain = new HashSet<int>();
foreach (var note in database.Notes)
{
if (note.UserMarkId != null)
{
userMarksToRetain.Add(note.UserMarkId.Value);
}
}
var countRemoved = 0;
foreach (var userMark in Enumerable.Reverse(database.UserMarks))
{
if (!userMarksToRetain.Contains(userMark.UserMarkId))
{
database.UserMarks.Remove(userMark);
++countRemoved;
}
}
return countRemoved;
}
19
View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
private static int RemoveUnderlining(Database database, HashSet<int> userMarkIdsToRemove, bool removereplacedociatedNotes)
{
var noteIdsToRemove = new HashSet<int>();
var tagMapIdsToRemove = new HashSet<int>();
if (userMarkIdsToRemove.Any())
{
foreach (var note in database.Notes)
{
if (note.UserMarkId == null)
{
continue;
}
if (userMarkIdsToRemove.Contains(note.UserMarkId.Value))
{
if (removereplacedociatedNotes)
{
noteIdsToRemove.Add(note.NoteId);
}
else
{
note.UserMarkId = null;
}
}
}
foreach (var tagMap in database.TagMaps)
{
if (tagMap.NoteId == null)
{
continue;
}
if (noteIdsToRemove.Contains(tagMap.NoteId.Value))
{
tagMapIdsToRemove.Add(tagMap.TagMapId);
}
}
}
database.UserMarks.RemoveAll(x => userMarkIdsToRemove.Contains(x.UserMarkId));
database.Notes.RemoveAll(x => noteIdsToRemove.Contains(x.NoteId));
database.TagMaps.RemoveAll(x => tagMapIdsToRemove.Contains(x.TagMapId));
return userMarkIdsToRemove.Count;
}
19
View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
public int RemoveNotesByTag(
BackupFile backup,
int[]? tagIds,
bool removeUntaggedNotes,
bool removereplacedociatedUnderlining,
bool removereplacedociatedTags)
{
if (backup == null)
{
throw new ArgumentNullException(nameof(backup));
}
tagIds ??= Array.Empty<int>();
var tagIdsHash = tagIds.ToHashSet();
var tagMapIdsToRemove = new HashSet<int>();
var noteIdsToRemove = new HashSet<int>();
var candidateUserMarks = new HashSet<int>();
if (removeUntaggedNotes)
{
// notes without a tag
foreach (var i in GetNotesWithNoTag(backup))
{
noteIdsToRemove.Add(i);
}
}
foreach (var tagMap in backup.Database.TagMaps)
{
if (tagIdsHash.Contains(tagMap.TagId) && tagMap.NoteId != null && tagMap.NoteId > 0)
{
tagMapIdsToRemove.Add(tagMap.TagMapId);
noteIdsToRemove.Add(tagMap.NoteId.Value);
var note = backup.Database.FindNote(tagMap.NoteId.Value);
if (note?.UserMarkId != null)
{
candidateUserMarks.Add(note.UserMarkId.Value);
}
}
}
backup.Database.TagMaps.RemoveAll(x => tagMapIdsToRemove.Contains(x.TagMapId));
backup.Database.TagMaps.RemoveAll(x => noteIdsToRemove.Contains(x.NoteId ?? 0));
backup.Database.Notes.RemoveAll(x => noteIdsToRemove.Contains(x.NoteId));
if (removereplacedociatedUnderlining)
{
RemoveUnderlining(backup.Database, candidateUserMarks);
}
if (removereplacedociatedTags)
{
RemoveSelectedTags(backup.Database, tagIdsHash);
}
return noteIdsToRemove.Count;
}
19
View Source File : StringGenerator.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
public void GenDefineCode(
int splitLines,
out Dictionary<string, int> strSplitMap,
out Dictionary<int, StringBuilder> codeMap,
out string strTypeDefs)
{
List<string> sortedStrs = GetSortedStrings();
strSplitMap = new Dictionary<string, int>();
codeMap = new Dictionary<int, StringBuilder>();
HashSet<int> lenSet = new HashSet<int>();
uint strTypeID = TypeGen.TypeMgr.GetTypeByName("System.String").GetCppTypeID();
int index = 0;
int counter = 0;
StringBuilder currSb = new StringBuilder();
codeMap.Add(index, currSb);
foreach (var str in sortedStrs)
{
lenSet.Add(str.Length);
strSplitMap.Add(str, index);
currSb.Append(GenStringCode(str, strTypeID));
++counter;
if (counter >= splitLines)
{
counter = 0;
++index;
currSb = new StringBuilder();
codeMap.Add(index, currSb);
}
}
Reset();
var prt = new CodePrinter();
foreach (var len in lenSet)
{
prt.AppendFormatLine("struct il2cppString_{0}\n{{",
len + 1);
++prt.Indents;
prt.AppendLine("IL2CPP_OBJECT_BODY;");
prt.AppendFormatLine("int len;\nuint16_t str[{0}];",
len + 1);
--prt.Indents;
prt.AppendLine("};");
}
strTypeDefs = prt.ToString();
}
19
View Source File : TypeGenerator.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
private void GenerateCompileUnits()
{
List<TypeCppCode> codeSorter = new List<TypeCppCode>(CodeMap.Values);
// 构建类型代码依赖关联
foreach (var cppCode in codeSorter)
{
foreach (string typeName in cppCode.DeclDependNames)
{
if (GetCodeFromMap(typeName, out var typeCode))
cppCode.DeclDependTypes.Add(typeCode);
}
cppCode.DeclDependNames = null;
foreach (string typeName in cppCode.ImplDependNames)
{
if (GetCodeFromMap(typeName, out var typeCode))
cppCode.ImplDependTypes.Add(typeCode);
}
cppCode.ImplDependNames = null;
}
CodeMap.Clear();
// 统计依赖计数
foreach (var cppCode in codeSorter)
{
// 预生成排序索引
cppCode.GetSortedID();
foreach (var typeCode in cppCode.DeclDependTypes)
++typeCode.DependCounter;
foreach (var typeCode in cppCode.ImplDependTypes)
++typeCode.DependCounter;
}
// 排序代码
codeSorter.Sort((x, y) =>
{
int cmp = x.GetSortedID().CompareTo(y.GetSortedID());
if (cmp == 0)
cmp = y.DependCounter.CompareTo(x.DependCounter);
return cmp;
});
// 划分编译单元
foreach (var cppCode in codeSorter)
{
var unit = GetCompileUnit();
unit.AddCode(cppCode);
cppCode.CompileUnit = unit;
}
StringGen.GenDefineCode(
100,
out var strSplitMap,
out var strCodeMap,
out string strTypeDefs);
// 生成代码
HashSet<string> dependSet = new HashSet<string>();
foreach (var unit in CompileUnits)
{
// 防止包含自身
dependSet.Add(unit.Name);
unit.DeclCode.Append("#pragma once\n");
unit.DeclCode.Append("#include \"il2cpp.h\"\n");
foreach (var cppCode in unit.CodeList)
{
// 生成头文件依赖包含
foreach (var typeCode in cppCode.DeclDependTypes)
{
string unitName = typeCode.CompileUnit.Name;
if (!dependSet.Contains(unitName))
{
dependSet.Add(unitName);
unit.DeclCode.AppendFormat("#include \"{0}.h\"\n",
unitName);
}
}
}
foreach (var cppCode in unit.CodeList)
{
// 拼接声明代码
unit.DeclCode.Append(cppCode.DeclCode);
cppCode.DeclCode = null;
cppCode.DeclDependTypes = null;
}
foreach (var cppCode in unit.CodeList)
{
// 生成源文件依赖包含
foreach (var typeCode in cppCode.ImplDependTypes)
{
string unitName = typeCode.CompileUnit.Name;
if (!dependSet.Contains(unitName))
{
dependSet.Add(unitName);
unit.ImplCode.AppendFormat("#include \"{0}.h\"\n",
unitName);
}
}
// 生成字符串包含
if (strSplitMap != null &&
cppCode.DependStrings.Count > 0)
{
HashSet<int> strUnitSet = new HashSet<int>();
foreach (string str in cppCode.DependStrings)
strUnitSet.Add(strSplitMap[str]);
cppCode.DependStrings = null;
foreach (var strUnitId in strUnitSet)
{
string strUnit = "StringUnit_" + strUnitId;
unit.ImplCode.AppendFormat("#include \"{0}.h\"\n",
strUnit);
}
}
}
foreach (var cppCode in unit.CodeList)
{
// 拼接实现代码
unit.ImplCode.Append(cppCode.ImplCode);
cppCode.ImplCode = null;
cppCode.ImplDependTypes = null;
}
// 如果包含内容则追加头文件
if (unit.ImplCode.Length > 0)
unit.ImplCode.Insert(0, string.Format("#include \"{0}.h\"\n", unit.Name));
unit.CodeList = null;
dependSet.Clear();
}
if (strTypeDefs.Length > 0)
{
foreach (var item in strCodeMap)
{
var strUnit = new CppCompileUnit("StringUnit_" + item.Key);
CompileUnits.Add(strUnit);
strUnit.DeclCode.Append("#pragma once\n");
strUnit.DeclCode.Append("#include \"StringTypes.h\"\n");
strUnit.DeclCode.Append(item.Value);
}
var strTypeDefUnit = new CppCompileUnit("StringTypes");
CompileUnits.Add(strTypeDefUnit);
strTypeDefUnit.DeclCode.Append("#pragma once\n");
strTypeDefUnit.DeclCode.Append("#include \"il2cpp.h\"\n");
strTypeDefUnit.DeclCode.Append(strTypeDefs);
}
// 添加初始化静态变量的函数
if (StaticInitBody.Length > 0)
{
var firstUnit = CompileUnits[0];
string initDecl = "void il2cpp_InitStaticVars()";
firstUnit.DeclCode.Append(initDecl + ";\n");
CodePrinter staticInitPrt = new CodePrinter();
staticInitPrt.Append(StaticInitDecl.ToString());
staticInitPrt.Append(initDecl);
staticInitPrt.AppendLine("\n{");
++staticInitPrt.Indents;
staticInitPrt.Append(StaticInitBody.ToString());
--staticInitPrt.Indents;
staticInitPrt.AppendLine("}");
firstUnit.ImplCode.Append(staticInitPrt);
}
}
19
View Source File : MethodX.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
public void AddLeaveTarget(int target)
{
if (LeaveTargets == null)
LeaveTargets = new HashSet<int>();
LeaveTargets.Add(target);
}
19
View Source File : ListView.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
private void SingleToggle(int index)
{
if (index < 0 || index >= _filteredList.Length)
{
return;
}
_noneSelected = false;
if (_selectedIndexes.Add(index))
{
_selectRangeStart = _selectRangeEnd = index;
}
else
{
_selectedIndexes.Remove(index);
_selectRangeStart = _selectRangeEnd = -1;
}
}
19
View Source File : ListView.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
private void SingleSelect(int index)
{
if (index < 0 || index >= _filteredList.Length)
{
return;
}
_noneSelected = false;
_selectRangeStart = _selectRangeEnd = index;
_selectedIndexes.Clear();
_selectedIndexes.Add(index);
}
See More Examples