Here are the examples of the csharp api System.Collections.Generic.IEnumerable.OrderBy(System.Func, System.Collections.Generic.IComparer) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1047 Examples
19
View Source File : MatchingEngine.cs
License : Apache License 2.0
Project Creator : Aaronontheweb
License : Apache License 2.0
Project Creator : Aaronontheweb
private void RebuildBidIndex()
{
// lowest possible sell == front of list
BidsByPrice = new SortedSet<Order>(_bids.Values.OrderBy(x => x, OrderPriceComparer.Instance));
}
19
View Source File : Monster_Awareness.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public virtual bool FindNextTarget()
{
stopwatch.Restart();
try
{
SelectTargetingTactic();
SetNextTargetTime();
var visibleTargets = GetAttackTargets();
if (visibleTargets.Count == 0)
{
if (MonsterState != State.Return)
MoveToHome();
return false;
}
// Generally, a creature chooses whom to attack based on:
// - who it was last attacking,
// - who attacked it last,
// - or who caused it damage last.
// When players first enter the creature's detection radius, however, none of these things are useful yet,
// so the creature chooses a target randomly, weighted by distance.
// Players within the creature's detection sphere are weighted by how close they are to the creature --
// the closer you are, the more chance you have to be selected to be attacked.
var prevAttackTarget = AttackTarget;
switch (CurrentTargetingTactic)
{
case TargetingTactic.None:
Console.WriteLine($"{Name}.FindNextTarget(): TargetingTactic.None");
break; // same as focused?
case TargetingTactic.Random:
// this is a very common tactic with monsters,
// although it is not truly random, it is weighted by distance
var targetDistances = BuildTargetDistance(visibleTargets);
AttackTarget = SelectWeightedDistance(targetDistances);
break;
case TargetingTactic.Focused:
break; // always stick with original target?
case TargetingTactic.LastDamager:
var lastDamager = DamageHistory.LastDamager?.TryGetAttacker() as Creature;
if (lastDamager != null)
AttackTarget = lastDamager;
break;
case TargetingTactic.TopDamager:
var topDamager = DamageHistory.TopDamager?.TryGetAttacker() as Creature;
if (topDamager != null)
AttackTarget = topDamager;
break;
// these below don't seem to be used in PY16 yet...
case TargetingTactic.Weakest:
// should probably shuffle the list beforehand,
// in case a bunch of levels of same level are in a group,
// so the same player isn't always selected
var lowestLevel = visibleTargets.OrderBy(p => p.Level).FirstOrDefault();
AttackTarget = lowestLevel;
break;
case TargetingTactic.Strongest:
var highestLevel = visibleTargets.OrderByDescending(p => p.Level).FirstOrDefault();
AttackTarget = highestLevel;
break;
case TargetingTactic.Nearest:
var nearest = BuildTargetDistance(visibleTargets);
AttackTarget = nearest[0].Target;
break;
}
//Console.WriteLine($"{Name}.FindNextTarget = {AttackTarget.Name}");
if (AttackTarget != null && AttackTarget != prevAttackTarget)
EmoteManager.OnNewEnemy(AttackTarget);
return AttackTarget != null;
}
finally
{
ServerPerformanceMonitor.AddToreplacedulativeEvent(ServerPerformanceMonitor.replacedulativeEventHistoryType.Monster_Awareness_FindNextTarget, stopwatch.Elapsed.TotalSeconds);
}
}
19
View Source File : VerificationHelper.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
public static IEnumerable<Diagnostic> GetNewDiagnostics(IEnumerable<Diagnostic> diagnostics, IEnumerable<Diagnostic> newDiagnostics)
{
var oldArray = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
var newArray = newDiagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
int oldIndex = 0;
int newIndex = 0;
while (newIndex < newArray.Length)
{
if (oldIndex < oldArray.Length && oldArray[oldIndex].Id == newArray[newIndex].Id)
{
++oldIndex;
++newIndex;
}
else
{
yield return newArray[newIndex++];
}
}
}
19
View Source File : DiagnosticVerifier.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private static Diagnostic[] SortDiagnostics(IEnumerable<Diagnostic> diagnostics)
{
return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
}
19
View Source File : SuppressionFile.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private static void AddMessagesToDoreplacedent(XDoreplacedent doreplacedent, IEnumerable<SuppressMessage> messages)
{
var comparer = new SuppressionMessageComparer();
var sortedMessages = messages.OrderBy(m => m, comparer);
foreach (var message in sortedMessages)
{
var xmlMessage = message.ToXml();
if (xmlMessage != null)
doreplacedent.Root.Add(xmlMessage);
}
}
19
View Source File : TreeCodeTemplate.custom.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
private IEnumerable<string> OrderedNamespaces()
{
return grammar.UsingNamespaces
.Append("System.Diagnostics.Codereplacedysis")
.Append("ExhaustiveMatching")
.Distinct()
.OrderBy(v => v, NamespaceComparer.Instance);
}
19
View Source File : StyleExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static IEnumerable<string> ContentStyles(IPortalViewContext portalViewContext, SiteMapNode node, IDictionary<string, object> cache, IEnumerable<string> except, IEnumerable<KeyValuePair<string, string>> only)
{
var styles = ContentStyles(portalViewContext, node, cache).ToArray();
string[] allDisplayModes;
string[] availableDisplayModes;
if (TryGetDisplayModes(out allDisplayModes, out availableDisplayModes))
{
var partialUrlTrie = new FileNameTrie(styles);
var displayModeComparer = new DisplayModeComparer(availableDisplayModes);
var groups = GetDisplayModeFileGroups(partialUrlTrie, allDisplayModes);
if (only != null)
{
return only.Select(o =>
{
var extensionless = Path.GetFileNameWithoutExtension(o.Key);
var matchGroup = groups.FirstOrDefault(s => string.Equals(s.Prefix, extensionless, StringComparison.OrdinalIgnoreCase));
if (matchGroup == null)
{
return o.Value;
}
var file = matchGroup.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
.OrderBy(f => f, displayModeComparer)
.FirstOrDefault();
return file == null ? o.Value : file.Name.Item1;
});
}
if (except != null)
{
return groups
.Where(group => !except.Any(e => string.Equals(Path.GetFileNameWithoutExtension(e), group.Prefix, StringComparison.OrdinalIgnoreCase)))
.Select(group => group.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
.OrderBy(f => f, displayModeComparer)
.FirstOrDefault())
.Where(f => f != null)
.Select(f => f.Name.Item1);
}
return groups
.Select(group => group.Where(f => availableDisplayModes.Contains(f.DisplayModeId))
.OrderBy(f => f, displayModeComparer)
.FirstOrDefault())
.Where(f => f != null)
.Select(f => f.Name.Item1);
}
if (only != null)
{
return only.Select(o =>
{
var match = styles.FirstOrDefault(s => string.Equals(s.Item2, o.Key, StringComparison.InvariantCultureIgnoreCase));
return match == null ? o.Value : match.Item1;
});
}
if (except != null)
{
return styles
.Where(s => !except.Any(e => string.Equals(e, s.Item2, StringComparison.InvariantCultureIgnoreCase)))
.Select(s => s.Item1);
}
return styles.Select(s => s.Item1);
}
19
View Source File : SubgridControlTemplate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override void InstantiateControlIn(HtmlControl container)
{
if (string.IsNullOrWhiteSpace(Metadata.ViewID)) return;
var context = CrmConfigurationManager.CreateContext(ContextName);
var portal = PortalCrmConfigurationManager.CreatePortalContext(ContextName);
var user = portal == null ? null : portal.User;
EnreplacedyMetadata = GetEnreplacedyMetadata(context);
var viewId = new Guid(Metadata.ViewID);
if (viewId == Guid.Empty) return;
var viewGuids = new[] { viewId };
if (Metadata.ViewEnableViewPicker && !string.IsNullOrWhiteSpace(Metadata.ViewIds))
{
var viewids = Metadata.ViewIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (viewids.Length >= 1)
{
viewGuids = Array.ConvertAll(viewids, Guid.Parse).AsEnumerable().OrderBy(o => o != viewId).ThenBy(o => o).ToArray();
}
}
Bindings[Metadata.ControlID + "CrmEnreplacedyId"] = new CellBinding
{
Get = () => null,
Set = obj =>
{
var id = obj.ToString();
Guid enreplacedyId;
if (!Guid.TryParse(id, out enreplacedyId)) return;
var subgridHtml = BuildGrid(container, context, viewGuids, viewId, enreplacedyId, user);
var subgrid = new HtmlGenericControl("div") { ID = Metadata.ControlID, InnerHtml = subgridHtml.ToString() };
subgrid.Attributes.Add("clreplaced", "subgrid");
container.Controls.Add(subgrid);
}
};
if (!container.Page.IsPostBack) return;
// On PostBack no databinding occurs so get the id from the viewstate stored on the CrmEnreplacedyFormView control.
var crmEnreplacedyId = Metadata.FormView.CrmEnreplacedyId;
if (crmEnreplacedyId == null) return;
var gridHtml = BuildGrid(container, context, viewGuids, viewId, (Guid)crmEnreplacedyId, user);
var subgridControl = new HtmlGenericControl("div") { ID = Metadata.ControlID, InnerHtml = gridHtml.ToString() };
subgridControl.Attributes.Add("clreplaced", "subgrid");
container.Controls.Add(subgridControl);
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private IOrderedEnumerable<Vector2> GetOpenSpots()
{
Farm farm = Game1.getFarm();
List<Vector2> clearSpots = new List<Vector2>();
for (int x = 0; x < farm.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < farm.map.Layers[0].LayerHeight; y++)
{
Tile tile = farm.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if (Vector2.Distance(Game1.player.getTileLocation(), new Vector2(x, y)) < Config.MaxDistanceSpawn && tile != null && farm.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && farm.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !farm.waterTiles[x,y] && !farm.objects.ContainsKey(new Vector2(x, y)))
{
clearSpots.Add(new Vector2(x, y));
}
}
}
return clearSpots.OrderBy(s => Game1.random.NextDouble());
}
19
View Source File : NodeManager.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public Task<NodeList> GetRandomNodesAsync(int maxCount)
{
var randomPeers = _nodes.OrderBy(x => RandomHelper.GetRandom()).Take(maxCount).Select(n => n.Value)
.ToList();
NodeList nodes = new NodeList();
nodes.Nodes.AddRange(randomPeers);
return Task.FromResult(nodes);
}
19
View Source File : DiagnosticVerifier.Helper.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
private static Diagnostic[] SortDistinctDiagnostics(IEnumerable<Diagnostic> diagnostics)
{
return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ThenBy(d => d.Id).ToArray();
}
19
View Source File : SpParameter.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
public static string CreateCacheKey(this SpParameter[] parameters, string spName)
{
if (!parameters?.Any() ?? true)
{
return $"{dbPrefix}{spName}";
}
return parameters?
.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase)
.Aggregate(
$"{dbPrefix}{spName}:",
(seed, pair) =>
{
var value = pair.Value is DateTime dateTime
? dateTime.Ticks.ToString()
: pair.Value.ToString();
return $"{seed}@{pair.Name}+{value}&";
});
}
19
View Source File : CodeFixVerifier.Helper.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
private static IEnumerable<Diagnostic> GetNewDiagnostics(IEnumerable<Diagnostic> diagnostics, IEnumerable<Diagnostic> newDiagnostics)
{
var oldArray = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
var newArray = newDiagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
var oldIndex = 0;
var newIndex = 0;
while (newIndex < newArray.Length)
{
if (oldIndex < oldArray.Length && oldArray[oldIndex].Id == newArray[newIndex].Id)
{
++oldIndex;
++newIndex;
}
else
{
yield return newArray[newIndex++];
}
}
}
19
View Source File : GeneratorTools.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal static string[] AddEmbeddedAirDefense(string[] units, AmountNR airDefenseLevel, DBEntryCoalition coalitionDB, Decade decade, List<string> unitMods)
{
int airDefenseLevelInt = (int)airDefenseLevel.Get();
// No luck this time, don't add anything
if (Toolbox.RandomDouble() >= Database.Instance.Common.AirDefense.AirDefenseLevels[airDefenseLevelInt].EmbeddedChance)
return units;
// Convert the unit array to an open-ended list so that units can be added
List<string> unitsList = new List<string>(units);
// Add some air defense units
int embeddedCount = Database.Instance.Common.AirDefense.AirDefenseLevels[airDefenseLevelInt].EmbeddedUnitCount.GetValue();
for (int i = 0; i < embeddedCount; i++)
unitsList.AddRange(
coalitionDB.GetRandomUnits(Toolbox.RandomFrom(EMBEDDED_AIR_DEFENSE_FAMILIES), decade, 1, unitMods));
if (unitsList.Count == 0) return new string[0];
// Randomize unit order so embbedded air defense units are not always at the end of the group
// but keep unit #0 at its place, because the first unit of the group is used to determine the group type, and we don't want
// a artillery platoon to be named "air defense bataillon" because the first unit is a AAA.
string unit0 = unitsList[0];
unitsList.RemoveAt(0);
unitsList = unitsList.OrderBy(x => Toolbox.RandomInt()).ToList();
unitsList.Insert(0, unit0);
return unitsList.ToArray();
}
19
View Source File : ThingsGenerator.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
private void AddPlayerStarts(DoomMap map, TileType[,] subTiles)
{
int x, y;
List<Point> entrances = new List<Point>();
// Spawn a single-player/coop entrance for each of the four players
for (int player = 1; player <= 4; player++)
{
bool foundAnEntrance = false;
// First try to look for a free "entrance" tile
for (x = 0; x < subTiles.GetLength(0); x+= MapGenerator.SUBTILE_DIVISIONS)
for (y = 0; y < subTiles.GetLength(1); y += MapGenerator.SUBTILE_DIVISIONS)
{
if (!foundAnEntrance && (subTiles[x, y] == TileType.Entrance))
{
Point entranceTile = new Point(x / MapGenerator.SUBTILE_DIVISIONS, y / MapGenerator.SUBTILE_DIVISIONS);
if (entrances.Contains(entranceTile)) continue; // Entrance already in use
AddThing(map, x / MapGenerator.SUBTILE_DIVISIONS, y / MapGenerator.SUBTILE_DIVISIONS, player);
entrances.Add(entranceTile);
foundAnEntrance = true;
}
}
if (foundAnEntrance) continue;
// No "entrance" tile found for this player, so...
if (FreeTiles.Count > 0)
{
Point tile;
// ...if no player entrance has been selected yet, spawn the player on a random free tile
if (entrances.Count == 0)
tile = Toolbox.RandomFromList(FreeTiles);
// ...else spawn the player on the nearest free tile from player 1 start
else
tile = (from Point t in FreeTiles select t).OrderBy(t => t.Distance(entrances[0])).First();
FreeTiles.Remove(tile);
AddThing(map, tile.X, tile.Y, player);
entrances.Add(tile);
foundAnEntrance = true;
}
if (foundAnEntrance) continue;
// No free spot, put the player start in the northwest map corner.
// Should never happen unless the map is entirely made of walls, doors or other unpreplacedable stuff.
// Might be outside a sector but at least the map won't crash with a "no player start found" error.
AddThing(map, player - 1, 0, player);
entrances.Add(new Point(player - 1, 0));
}
}
19
View Source File : JsonSchemaNode.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public static string GetId(IEnumerable<JsonSchema> schemata)
{
return string.Join("-", schemata.Select(s => s.InternalId).OrderBy(id => id, StringComparer.Ordinal).ToArray());
}
19
View Source File : RequestPit.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static void Main()
{
//if (pitRequestActive) { Game.LogTrivial("PIT request already active"); return; }
GameFiber.StartNew(delegate
{
if (!Game.LocalPlayer.Character.IsInAnyVehicle(false)) { return; }
if (Functions.GetActivePursuit() == null) { return; }
List<Ped> eligiblePeds = Functions.GetPursuitPeds(Functions.GetActivePursuit()).Where(x => x.DistanceTo(Game.LocalPlayer.Character) < 55f && x.IsInAnyVehicle(false)).ToList();
Game.LogTrivial(eligiblePeds.Count.ToString());
if (eligiblePeds.Count > 0)
{
Vehicle targetVeh = eligiblePeds.OrderBy(x => x.DistanceTo(Game.LocalPlayer.Character.GetOffsetPositionFront(4f))).First().CurrentVehicle;
Ped targetPed = targetVeh.Driver;
Vehicle[] nearbyVehs = targetPed.Exists() ? targetPed.GetNearbyVehicles(16) : Game.LocalPlayer.Character.GetNearbyVehicles(16);
int NearbyOccupiedCivilianVehsCount = 0;
foreach (Vehicle veh in nearbyVehs)
{
if (veh.Exists())
{
if (veh.HasDriver)
{
if (!veh.Hreplacediren)
{
NearbyOccupiedCivilianVehsCount++;
}
}
}
}
Game.DisplayNotification("~b~" + PoliceSmartRadio.PlayerName + "~s~: Dispatch, requesting to perform ~r~PIT~s~.");
if (NearbyOccupiedCivilianVehsCount > 7)
{
GameFiber.Wait(4000);
Game.DisplayNotification("~b~Dispatch ~w~: " + PoliceSmartRadio.PlayerName + ", traffic is ~r~too busy.~s~ You ~r~aren't clear~s~ to ~r~PIT, ~w~over.");
return;
}
else
{
GameFiber.Wait(4000);
Game.DisplayNotification("~b~Dispatch ~w~: " + PoliceSmartRadio.PlayerName + " you are clear at this time to ~r~PIT, ~w~over.");
}
bool pitComplete = false;
Stopwatch standstillStopwatch = new Stopwatch();
standstillStopwatch.Start();
while (!pitComplete)
{
GameFiber.Yield();
if ((targetVeh.Speed <= 0.8f) && (Vector3.Distance(targetVeh.Position, Game.LocalPlayer.Character.Position) < 18f))
{
if (standstillStopwatch.ElapsedMilliseconds > 3500)
{
targetVeh.EngineHealth = 0.0f;
Game.DisplayNotification("~b~" + PoliceSmartRadio.PlayerName + "~s~: PIT successful, located at~b~ " + World.GetStreetName(Game.LocalPlayer.Character.Position));
pitComplete = true;
}
}
else
{
standstillStopwatch.Restart();
}
if (!targetVeh.HasDriver)
{
break;
}
}
}
});
}
19
View Source File : DiagnosticVerifier.Helper.cs
License : MIT License
Project Creator : AlexGhiondea
License : MIT License
Project Creator : AlexGhiondea
private static Diagnostic[] SortDiagnostics(IEnumerable<Diagnostic> diagnostics)
{
return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
}
19
View Source File : MeshOperator.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public Vector3 NearestLocalSurfacePoint(Vector3 localPoint)
{
var p = localPoint;
var tris = Math.GetNearestVerticesTriangle(p, meshVertices, meshTriangles);
var pds = new List<Vector3>();
for(int i = 0; i < tris.Length; i += 3)
{
var i0 = i;
var i1 = i + 1;
var i2 = i + 2;
pds.Add(Math.TriangleSpaceProjection(p, tris[i0], tris[i1], tris[i2]));
}
return pds.OrderBy(t => Vector3.Distance(p, t)).First();
}
19
View Source File : GetRequest.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public string BuildParams()
{
if (_params.Count == 0)
{
return string.Empty;
}
StringBuilder sb = new StringBuilder();
foreach (var para in _params.OrderBy(i => i.Key, StringComparer.Ordinal))
{
sb.Append('&');
sb.Append(para.Key).Append('=').Append(para.Value);
}
return sb.ToString().Substring(1);
}
19
View Source File : TestPriorityOrderer.cs
License : MIT License
Project Creator : aliyun
License : MIT License
Project Creator : aliyun
public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases)
where TTestCase : ITestCase
{
var cases = testCases.ToArray();
var caseDepends = cases.ToDictionary(
x => x.TestMethod.Method.Name,
x =>
(
depends: x.TestMethod.Method
.GetCustomAttributes(typeof(TestPriorityAttribute).replacedemblyQualifiedName)
.SingleOrDefault()?
.GetNamedArgument<String[]>("DependsOn") ?? EmptyDepends,
// Use Int64 to prevent the after-last case.
priority: (Int64) (x.TestMethod.Method
.GetCustomAttributes(typeof(TestPriorityAttribute).replacedemblyQualifiedName)
.SingleOrDefault()?
.GetNamedArgument<Int32>("Priority") ?? 0)
));
var allCases = caseDepends
.ToDictionary(x => x.Key, x => new DependNode(x.Key));
// Construct hierarchy
foreach (var (current, (depends, _)) in caseDepends)
{
foreach (var depend in depends)
{
if (allCases.TryGetValue(depend, out var @case))
{
@case.TryAdd(allCases[current]);
}
}
}
var prioritizedCases = allCases.ToDictionary(
x => x.Key,
x => caseDepends[x.Key].depends.IsEmpty()
? caseDepends[x.Key].priority // Root nodes use defined priority.
: (Int64?)null); // Child nodes use hierarchy related priority.
// Process all roots.
var rootNodes = allCases
// No depends
.Where(x => caseDepends[x.Key].depends.IsEmpty())
// Contain children
.Where(x => allCases[x.Key].Children.IsNotEmpty())
.ToArray(); // Freeze for debugging.
foreach (var (rootName, rootNode) in rootNodes)
{
// Circular validation context.
var path = new Stack<String>();
void DfsProcessHierarchy(IEnumerable<KeyValuePair<String, DependNode>> nodes, Int64 priority)
{
foreach (var (currentName, currentNode) in nodes)
{
// Check cirular reference.
if (path.Contains(currentName))
{
throw new ArgumentException($"Circular reference detect: [{String.Join("->", path.Append(currentName))}]");
}
path.Push(currentName);
prioritizedCases[currentName] = Math.Max(prioritizedCases[currentName] ?? priority, priority);
// Deep-First traverse
DfsProcessHierarchy(currentNode.Children, priority + 1);
path.Pop();
}
}
path.Push(rootName);
var rootPriority = prioritizedCases[rootName] ?? 0;
DfsProcessHierarchy(rootNode.Children, rootPriority + 1);
path.Pop();
}
var orderedCases = cases
.OrderBy(x => prioritizedCases[x.TestMethod.Method.Name] ?? 0)
.ToArray();
return orderedCases;
}
19
View Source File : PhysicsRemoteFPSAgentController_partial_ExpRoom.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
public void PointOnObjectsCollidersClosestToPoint(
string objectId, Vector3 point
) {
if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) {
errorMessage = $"Cannot find object with id {objectId}.";
actionFinishedEmit(false);
return;
}
SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId];
List<Vector3> closePoints = new List<Vector3>();
foreach (Collider c in target.GetComponentsInChildren<Collider>()) {
if (c.enabled && !c.isTrigger) {
closePoints.Add(c.ClosestPoint(point));
}
}
closePoints = closePoints.OrderBy(x => Vector3.Distance(point, x)).ToList();
#if UNITY_EDITOR
foreach (Vector3 p in closePoints) {
Debug.Log($"{p} has dist {Vector3.Distance(p, point)}");
}
#endif
actionFinishedEmit(true, closePoints);
}
19
View Source File : DroneFPSAgentController.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
public Vector3[] SeekTwoPos(Vector3[] shuffledCurrentlyReachable) {
Vector3[] output = new Vector3[2];
List<float> y_candidates = new List<float>(new float[] { 1.0f, 1.25f, 1.5f });
foreach (Vector3 p in shuffledCurrentlyReachable) {
foreach (Vector3 p2 in shuffledCurrentlyReachable) {
if (!p.Equals(p2)) {
if (p2.z >= (p.z + 1.5f) && Mathf.Abs(p.z - p2.z) <= 2.5f) {
// if(Mathf.Abs(p.x-p2.x) < 0.5*Mathf.Abs(p.z-p2.z)){
// if(Mathf.Abs(p.x-p2.x) == 0){
if (Mathf.Abs(p.x - p2.x) <= 0.5) {
float y = y_candidates.OrderBy(x => systemRandom.Next()).ToArray()[0];
output[0] = new Vector3(p.x, 1.0f, p.z);
output[1] = new Vector3(p2.x, y, p2.z);
return output;
}
}
}
}
}
return output;
}
19
View Source File : PhysicsRemoteFPSAgentController_partial_ExpRoom.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
public void PointOnObjectsMeshClosestToPoint(
string objectId, Vector3 point
) {
if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) {
errorMessage = $"Cannot find object with id {objectId}.";
actionFinishedEmit(false);
return;
}
SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId];
List<Vector3> points = new List<Vector3>();
foreach (MeshFilter mf in target.GetComponentsInChildren<MeshFilter>()) {
foreach (Vector3 v in mf.mesh.vertices) {
points.Add(mf.transform.TransformPoint(v));
}
}
points = points.OrderBy(x => Vector3.Distance(point, x)).ToList();
#if UNITY_EDITOR
foreach (Vector3 p in points) {
Debug.Log($"{p} has dist {Vector3.Distance(p, point)}");
}
#endif
actionFinishedEmit(true, points);
}
19
View Source File : CanonicalRequestBuilder.cs
License : MIT License
Project Creator : AllocZero
License : MIT License
Project Creator : AllocZero
private static void AppendSortedQueryString(ref NoAllocStringBuilder builder, string query)
{
if (!string.IsNullOrEmpty(query))
{
var queryParameters = HttpUtility.ParseQueryString(query);
var parsedParameters = new Dictionary<string, List<string>>(queryParameters.Count);
foreach (string parameterName in queryParameters)
{
var parameterValues = queryParameters.GetValues(parameterName)!;
if (!parsedParameters.TryGetValue(parameterName, out var cachedParameterValues))
parsedParameters[parameterName] = parameterValues.ToList();
else
cachedParameterValues.AddRange(parameterValues);
}
var isFirst = true;
foreach (var parameter in parsedParameters.OrderBy(x => x.Key, StringComparer.Ordinal))
{
foreach (var parameterValue in parameter.Value.OrderBy(x => x, StringComparer.Ordinal))
{
if (!isFirst)
builder.Append('&');
builder.Append(UrlEncoder.Encode(parameter.Key, false));
builder.Append('=');
builder.Append(UrlEncoder.Encode(parameterValue, false));
isFirst = false;
}
}
}
builder.Append('\n');
}
19
View Source File : CollectionExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
private static List<T> GetRandomList<T>([NotNull] this IList<T> list)
{
return Enumerable.Range(0, list.Count).OrderBy(_ => Helper.SecurityHelper.Random.Next(list.Count)).Select(i => list[i]).ToList();
}
19
View Source File : InfoKeyword.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public static int GetCollectionHashCode(IEnumerable<KeyValuePair<string, string>> collection)
{
return collection.OrderBy(kvp => kvp.Key, StringComparer.Ordinal)
.Aggregate(0, (current, kvp) =>
{
unchecked
{
var code = (current * 397) ^ kvp.Key.GetHashCode();
code = (code * 397) ^ (kvp.Value?.GetHashCode() ?? 0);
return code;
}
});
}
19
View Source File : TextsKeyword.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public static int GetCollectionHashCode(IEnumerable<KeyValuePair<string, JsonSchema>> collection)
{
return collection.OrderBy(kvp => kvp.Key, StringComparer.Ordinal)
.Aggregate(0, (current, kvp) =>
{
unchecked
{
var code = (current * 397) ^ kvp.Key.GetHashCode();
code = (code * 397) ^ (kvp.Value?.GetHashCode() ?? 0);
return code;
}
});
}
19
View Source File : Generator.cs
License : MIT License
Project Creator : altskop
License : MIT License
Project Creator : altskop
public static void Generate(string path, string output)
{
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
if (di.Exists)
{
foreach (var file in di.GetFiles())
{
XDoreplacedent xml =XDoreplacedent.Load(file.FullName);
var list = xml.Root.Elements().Reverse();
List< Element > datas = new List<Element>();
foreach (var m in list)
{
Element em = new Element();
em.offset = int.Parse(m.Attribute("Offset").Value);
em.varType = m.Attribute("Vartype").Value;
em.sizeOf = int.Parse(m.Attribute("Bytesize").Value);
em.desc = m.Attribute("Description").Value;
em.displayMethod = m.Attribute("DisplayMethod").Value;
datas.Add(em);
}
datas = datas.OrderBy(x => x.offset).ToList();
Gen(file.Name.Split('.')[0], datas, output);
}
}
}
19
View Source File : PolyPathfinder.cs
License : MIT License
Project Creator : altskop
License : MIT License
Project Creator : altskop
public List<Waypoint> findPath(Vertex start, Vertex end)
{
List<Waypoint> waypoints = new List<Waypoint>();
// First verify if both the start and end points of the path are inside the polygon
foreach (Polygon polygon in polygons)
{
if (!Inside(polygon, start)) { start = findClosestVertex(start, polygons); }
if (!Inside(polygon, end)) { end = findClosestVertex(start, polygons); }
//if (!Inside(polygon, start)) { return null; }
//if (!Inside(polygon, end)) { return null; }
}
// Then start by checking if both points are in line-of-sight.
if (InLineOfSight(polygons, start, end))
{
waypoints.Add(new Waypoint(start));
waypoints.Add(new Waypoint(end));
return waypoints;
}
var openList = new List<PathfindingNode>();
var closedList = new List<PathfindingNode>();
int g = 0;
// start by adding the original position to the open list
PathfindingNode startNode = new PathfindingNode(start);
startNode.findVisibleNodes(polygons);
PathfindingNode endNode = new PathfindingNode(end);
endNode.findVisibleNodes(polygons);
startNode.updateF(startNode, endNode);
openList.Add(startNode);
while (openList.Count > 0)
{
Console.WriteLine($"openList.Count: {openList.Count}");
var checkTile = openList.OrderBy(x => x.F).First();
// algorithm's logic goes here
if (endNode.visiblePoints.Any(x => x.x == checkTile.X && x.y == checkTile.Y))
{
waypoints.Add(new Waypoint(end));
while(checkTile.parent != null)
{
//waypoints.Add(new Waypoint(checkTile.X, checkTile.Y));
var resultingVertex = findClosestVertex(new Vertex(checkTile), this.waypoints);
var waypoint = generateWaypoint(resultingVertex.x, resultingVertex.y, polygons, 20);
waypoints.Add(waypoint);
Vertex middlePoint = findClosestVertex(((new Vertex(checkTile) + new Vertex(checkTile.parent)) / 2f), this.waypoints);
if (Inside(polygons, middlePoint))
{
waypoint = generateWaypoint(middlePoint.x, middlePoint.y, polygons, 15);
waypoints.Add(waypoint);
}
checkTile = checkTile.parent;
}
waypoints.Reverse();
return waypoints;
//We can actually loop through the parents of each tile to find our exact path which we will show shortly.
//return;
}
closedList.Add(checkTile);
openList.Remove(checkTile);
var walkableTiles = checkTile.visiblePoints;
foreach (var walkableTile in walkableTiles)
{
//We have already visited this tile so we don't need to do so again!
if (closedList.Any(x => x.X == walkableTile.x && x.Y == walkableTile.y))
continue;
//It's already in the active list, but that's OK, maybe this new tile has a better value (e.g. We might zigzag earlier but this is now straighter).
if (openList.Any(x => x.X == walkableTile.x && x.Y == walkableTile.y))
{
var existingTile = openList.First(x => x.X == walkableTile.x && x.Y == walkableTile.y);
if (existingTile.F > checkTile.F)
{
openList.Remove(existingTile);
openList.Add(new PathfindingNode(checkTile, walkableTile, startNode, endNode));
}
}
else
{
//We've never seen this tile before so add it to the list.
openList.Add(new PathfindingNode(checkTile, walkableTile, startNode, endNode));
}
}
}
Console.WriteLine("Couldn't build a path");
return null;
}
19
View Source File : MemberInfoExtensions.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public static IEnumerable<MemberInfo> GetMembersInTypeHierarchyInOrder(this Type type, BindingFlags bindingFlags)
{
return type.GetMembersInTypeHierarchy(bindingFlags)
.GroupBy(m => m.DeclaringType)
.Select(g => g.OrderBy(m => m.GetCustomAttribute<ShaderMemberAttribute>()?.Order))
.SelectMany(m => m);
}
19
View Source File : MemberInfoExtensions.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public static IEnumerable<MemberInfo> GetMembersInOrder(this Type type, BindingFlags bindingFlags)
{
IEnumerable<MemberInfo> members = type.GetShaderMembers(bindingFlags).OrderBy(m => m.GetCustomAttribute<ShaderMemberAttribute>()?.Order);
if (type.IsDefined(typeof(ShaderContractAttribute)))
{
members = members.Where(m => m.IsDefined(typeof(ShaderMemberAttribute)));
}
return members;
}
19
View Source File : CodeFixVerifier.Helper.cs
License : MIT License
Project Creator : amis92
License : MIT License
Project Creator : amis92
private static IEnumerable<Diagnostic> GetNewDiagnostics(IEnumerable<Diagnostic> diagnostics, IEnumerable<Diagnostic> newDiagnostics)
{
var oldArray = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
var newArray = newDiagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
int oldIndex = 0;
int newIndex = 0;
while (newIndex < newArray.Length)
{
if (oldIndex < oldArray.Length && oldArray[oldIndex].Id == newArray[newIndex].Id)
{
++oldIndex;
++newIndex;
}
else
{
yield return newArray[newIndex++];
}
}
}
19
View Source File : CodeFixVerifier.Helper.cs
License : MIT License
Project Creator : angularsen
License : MIT License
Project Creator : angularsen
private static IEnumerable<Diagnostic> GetNewDiagnostics(IEnumerable<Diagnostic> diagnostics, IEnumerable<Diagnostic> newDiagnostics)
{
var oldArray = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
var newArray = newDiagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
var oldIndex = 0;
var newIndex = 0;
while (newIndex < newArray.Length)
if (oldIndex < oldArray.Length && oldArray[oldIndex].Id == newArray[newIndex].Id)
{
++oldIndex;
++newIndex;
}
else
{
yield return newArray[newIndex++];
}
}
19
View Source File : BuilderPlug.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
public void UpdateSoundEnvironments(object sender, DoWorkEventArgs e)
{
List<Sector> sectorstocheck = new List<Sector>();
List<Sector> checkedsectors = new List<Sector>();
List<Sector> allsectors = new List<Sector>();
BackgroundWorker worker = sender as BackgroundWorker;
List<FlatVertex> vertsList = new List<FlatVertex>();
Dictionary<Thing, PixelColor> secolor = new Dictionary<Thing, PixelColor>();
Dictionary<Thing, int> senumber = new Dictionary<Thing, int>();
soundenvironments.Clear();
blockinglinedefs.Clear();
SoundEnvironmentMode.SoundEnvironmentPanel.BeginUpdate(); //mxd
// Keep track of all the sectors in the map. Sectors that belong to a sound environment
// will be removed from the list, so in the end only sectors that don't belong to any
// sound environment will be in this list
foreach(Sector s in General.Map.Map.Sectors) allsectors.Add(s);
List<Thing> soundenvironmenthings = GetSoundEnvironmentThings(General.Map.Map.Sectors.ToList());
int numthings = soundenvironmenthings.Count;
// replacedign each thing a color and a number, so each sound environment will always have the same color
// and id, no matter in what order they are discovered
for(int i = 0; i < soundenvironmenthings.Count; i++)
{
//mxd. Make sure same environments use the same color
int seid = (soundenvironmenthings[i].Args[0] << 8) + soundenvironmenthings[i].Args[1];
secolor[soundenvironmenthings[i]] = distinctcolors[seid % distinctcolors.Count];
senumber.Add(soundenvironmenthings[i], i + 1);
}
while(soundenvironmenthings.Count > 0 && !worker.CancellationPending)
{
// Sort things by distance to center of the screen, so that sound environments the user want to look at will (hopefully) be discovered first
Vector2D center = General.Map.Renderer2D.DisplayToMap(new Vector2D(General.Interface.Display.Width / 2f, General.Interface.Display.Height / 2f));
soundenvironmenthings = soundenvironmenthings.OrderBy(o => Math.Abs(Vector2D.Distance(center, o.Position))).ToList();
Thing thing = soundenvironmenthings[0];
if(thing.Sector == null) thing.DetermineSector();
// Ignore things that are outside the map
if(thing.Sector == null)
{
soundenvironmenthings.Remove(thing);
continue;
}
SoundEnvironment environment = new SoundEnvironment();
// Add initial sector. Additional adjacant sectors will be added later
// as they are discovered
sectorstocheck.Add(thing.Sector);
while(sectorstocheck.Count > 0)
{
Sector sector = sectorstocheck[0];
if(!environment.Sectors.Contains(sector)) environment.Sectors.Add(sector);
if(!checkedsectors.Contains(sector)) checkedsectors.Add(sector);
sectorstocheck.Remove(sector);
allsectors.Remove(sector);
// Find adjacant sectors and add them to the list of sectors to check if necessary
foreach(Sidedef sd in sector.Sidedefs)
{
if(LinedefBlocksSoundEnvironment(sd.Line))
{
if(!environment.Linedefs.Contains(sd.Line)) environment.Linedefs.Add(sd.Line);
continue;
}
if(sd.Other == null) continue;
Sector oppositesector = (sd.Line.Front.Sector == sector ? sd.Line.Back.Sector : sd.Line.Front.Sector);
if(!sectorstocheck.Contains(oppositesector) && !checkedsectors.Contains(oppositesector))
sectorstocheck.Add(oppositesector);
}
}
// Get all things that are in the current sound environment...
environment.Things = GetSoundEnvironmentThings(environment.Sectors);
// ... and remove them from the list of sound environment things to check, because we know that
// they already belong to a sound environment
foreach(Thing t in environment.Things)
{
if(soundenvironmenthings.Contains(t)) soundenvironmenthings.Remove(t);
}
// Set color and id of the sound environment
environment.Color = secolor[environment.Things[0]];
environment.ID = senumber[environment.Things[0]];
// Create the data for the overlay geometry
List<FlatVertex> severtslist = new List<FlatVertex>(environment.Sectors.Count * 3); //mxd
foreach(Sector s in environment.Sectors)
{
FlatVertex[] fv = new FlatVertex[s.FlatVertices.Length];
s.FlatVertices.CopyTo(fv, 0);
for(int j = 0; j < fv.Length; j++) fv[j].c = environment.Color.WithAlpha(128).ToInt();
vertsList.AddRange(fv);
severtslist.AddRange(fv); //mxd
// Get all Linedefs that will block sound environments
foreach(Sidedef sd in s.Sidedefs)
{
if(!LinedefBlocksSoundEnvironment(sd.Line)) continue;
lock(blockinglinedefs)
{
blockinglinedefs.Add(sd.Line);
}
}
}
//mxd. Store sector environment verts
environment.SectorsGeometry = severtslist.ToArray();
// Update the overlay geometry with the newly added sectors
if(overlayGeometry == null)
{
overlayGeometry = vertsList.ToArray();
}
else
{
lock(overlayGeometry)
{
overlayGeometry = vertsList.ToArray();
}
}
environment.Things = environment.Things.OrderBy(o => o.Index).ToList();
environment.Linedefs = environment.Linedefs.OrderBy(o => o.Index).ToList();
//mxd. Find the first non-dormant thing
Thing activeenv = null;
foreach(Thing t in environment.Things)
{
if(!ThingDormant(t))
{
activeenv = t;
break;
}
}
//mxd. Update environment name
if(activeenv != null)
{
foreach(KeyValuePair<string, KeyValuePair<int, int>> group in General.Map.Data.Reverbs)
{
if(group.Value.Key == activeenv.Args[0] && group.Value.Value == activeenv.Args[1])
{
environment.Name = group.Key + " (" + activeenv.Args[0] + " " + activeenv.Args[1] + ")";
break;
}
}
//mxd. No suitable name found?..
if(environment.Name == SoundEnvironment.DEFAULT_NAME)
{
environment.Name += " (" + activeenv.Args[0] + " " + activeenv.Args[1] + ")";
}
}
//mxd. Still no suitable name?..
if(environment.Name == SoundEnvironment.DEFAULT_NAME) environment.Name += " " + environment.ID;
lock(soundenvironments)
{
soundenvironments.Add(environment);
}
// Tell the worker that discovering a sound environment is finished. This will update the tree view, and also
// redraw the interface, so the sectors of this sound environment are colored
worker.ReportProgress((int)((1.0f - (soundenvironmenthings.Count / (float)numthings)) * 100), environment);
}
// Create overlay geometry for sectors that don't belong to a sound environment
foreach(Sector s in allsectors)
{
FlatVertex[] fv = new FlatVertex[s.FlatVertices.Length];
s.FlatVertices.CopyTo(fv, 0);
for(int j = 0; j < fv.Length; j++) fv[j].c = NoSoundColor.WithAlpha(128).ToInt();
vertsList.AddRange(fv);
}
if(overlayGeometry == null)
{
overlayGeometry = vertsList.ToArray();
}
else
{
lock(overlayGeometry)
{
overlayGeometry = vertsList.ToArray();
}
}
soundenvironmentisupdated = true;
SoundEnvironmentMode.SoundEnvironmentPanel.EndUpdate(); //mxd
}
19
View Source File : ProgressBar.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public Color AvailableColor(
double value)
{
var c = this.ColorRange
.Where(x => x.IsApply(value))
.OrderBy(x => x.Min)
.FirstOrDefault()?
.Color;
return c ?? Colors.Transparent;
}
19
View Source File : QueryExtensor.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
public static async Task<PagedQuery<T>> PageBy<T>(this IQueryable<T> query, string filter, string sort, int? skip = 0, int? take = 50)
{
if (!string.IsNullOrEmpty(filter))
{
query = query.Where(filter);
}
if (!string.IsNullOrEmpty(sort))
{
query = query.OrderBy(sort);
}
var count = await query.CountAsync();
return query.PageBy(count, skip ?? 0, take ?? 100);
}
19
View Source File : PKMPreview.cs
License : MIT License
Project Creator : architdate
License : MIT License
Project Creator : architdate
public static void ExportCSV(IEnumerable<PKMPreview> pklist, string path)
{
var sortedprev = pklist.OrderBy(p => p.Species).ToList();
// Todo: Complete function. POC
var sb = new StringBuilder();
const string headers = "Nickname, Species, Nature, Gender, ESV, Hidden Power, Ability, Move 1, Move 2, Move 3, Move 4, Held Item, HP, ATK, DEF, SPA, SPD, SPE, Met Location, Egg Location, Ball, OT, Version, OT Language, Legal, Country, Region, 3DS Region, PID, EC, HP IVs, ATK IVs, DEF IVs, SPA IVs, SPD IVs, SPE IVs, EXP, Level, Markings, Handling Trainer, Met Level, Shiny, TID, SID, Friendship, Met Year, Met Month, Met Day";
sb.AppendLine(headers);
foreach (PKMPreview p in sortedprev)
{
var country = "N/A";
var region = "N/A";
var DSRegion = "N/A";
if (p.pkm is IGeoTrack gt)
{
country = gt.Country.ToString();
region = gt.Region.ToString();
DSRegion = gt.ConsoleRegion.ToString();
}
sb.AppendLine(string.Join(",", p.Nickname, p.Species, p.Nature, p.Gender, p.ESV, p.HP_Type, p.Ability,
p.Move1, p.Move2, p.Move3, p.Move4, p.HeldItem, p.HP, p.ATK, p.DEF, p.SPA, p.SPD, p.SPE, p.MetLoc,
p.EggLoc, p.Ball, p.OT, p.Version, p.OTLang, p.Legal, country, region, DSRegion,
p.PID, p.EC, p.HP_IV.ToString(), p.ATK_IV.ToString(), p.DEF_IV.ToString(), p.SPA_IV.ToString(),
p.SPD_IV.ToString(), p.SPE_IV.ToString(), p.EXP.ToString(), p.Level.ToString(),
p.Markings.ToString(), p.NotOT, p.MetLevel.ToString(), p.IsShiny.ToString(), p.TID.ToString(),
p.SID.ToString(), p.Friendship.ToString(), p.Met_Year.ToString(), p.Met_Month.ToString(),
p.Met_Day.ToString()));
}
File.WriteAllText(Path.Combine(path, "boxdump.csv"), sb.ToString(), Encoding.UTF8);
}
19
View Source File : MahjongLogic.cs
License : MIT License
Project Creator : ArcturusZhang
License : MIT License
Project Creator : ArcturusZhang
public static IOrderedEnumerable<KeyValuePair<int, int>> SortPointsAndPlaces(IEnumerable<int> points)
{
return points.Select((p, i) => new KeyValuePair<int, int>(p, i))
.OrderBy(key => key, new PointsComparer());
}
19
View Source File : OrderEvaluator.cs
License : MIT License
Project Creator : ardalis
License : MIT License
Project Creator : ardalis
public IQueryable<T> GetQuery<T>(IQueryable<T> query, ISpecification<T> specification) where T : clreplaced
{
if (specification.OrderExpressions != null)
{
if (specification.OrderExpressions.Where(x => x.OrderType == OrderTypeEnum.OrderBy ||
x.OrderType == OrderTypeEnum.OrderByDescending).Count() > 1)
{
throw new DuplicateOrderChainException();
}
IOrderedQueryable<T>? orderedQuery = null;
foreach (var orderExpression in specification.OrderExpressions)
{
if (orderExpression.OrderType == OrderTypeEnum.OrderBy)
{
orderedQuery = query.OrderBy(orderExpression.KeySelector);
}
else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending)
{
orderedQuery = query.OrderByDescending(orderExpression.KeySelector);
}
else if (orderExpression.OrderType == OrderTypeEnum.ThenBy)
{
orderedQuery = orderedQuery.ThenBy(orderExpression.KeySelector);
}
else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending)
{
orderedQuery = orderedQuery.ThenByDescending(orderExpression.KeySelector);
}
}
if (orderedQuery != null)
{
query = orderedQuery;
}
}
return query;
}
19
View Source File : OrderEvaluator.cs
License : MIT License
Project Creator : ardalis
License : MIT License
Project Creator : ardalis
public IEnumerable<T> Evaluate<T>(IEnumerable<T> query, ISpecification<T> specification)
{
if (specification.OrderExpressions != null)
{
if (specification.OrderExpressions.Where(x => x.OrderType == OrderTypeEnum.OrderBy ||
x.OrderType == OrderTypeEnum.OrderByDescending).Count() > 1)
{
throw new DuplicateOrderChainException();
}
IOrderedEnumerable<T>? orderedQuery = null;
foreach (var orderExpression in specification.OrderExpressions)
{
if (orderExpression.OrderType == OrderTypeEnum.OrderBy)
{
orderedQuery = query.OrderBy(orderExpression.KeySelector.Compile());
}
else if (orderExpression.OrderType == OrderTypeEnum.OrderByDescending)
{
orderedQuery = query.OrderByDescending(orderExpression.KeySelector.Compile());
}
else if (orderExpression.OrderType == OrderTypeEnum.ThenBy)
{
orderedQuery = orderedQuery.ThenBy(orderExpression.KeySelector.Compile());
}
else if (orderExpression.OrderType == OrderTypeEnum.ThenByDescending)
{
orderedQuery = orderedQuery.ThenByDescending(orderExpression.KeySelector.Compile());
}
}
if (orderedQuery != null)
{
query = orderedQuery;
}
}
return query;
}
19
View Source File : SpecificationEvaluator.cs
License : MIT License
Project Creator : ardalis
License : MIT License
Project Creator : ardalis
public static IQueryable<T> GetQuery(IQueryable<T> inputQuery, BaseSpecification<T> specification)
{
var query = inputQuery;
// modify the IQueryable using the specification's criteria expression
if (specification.Criteria != null)
{
query = query.Where(specification.Criteria);
}
// Includes all expression-based includes
query = specification.Includes.Aggregate(query,
(current, include) => current.Include(include));
// Include any string-based include statements
query = specification.IncludeStrings.Aggregate(query,
(current, include) => current.Include(include));
// Apply ordering if expressions are set
if (specification.OrderBy != null)
{
query = query.OrderBy(specification.OrderBy);
}
else if (specification.OrderByDescending != null)
{
query = query.OrderByDescending(specification.OrderByDescending);
}
// Apply paging if enabled
if (specification.isPagingEnabled)
{
query = query.Skip(specification.Skip)
.Take(specification.Take);
}
return query;
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : arslanaybars
License : MIT License
Project Creator : arslanaybars
public static (IQueryable<T>, int) ApplyFop<T>(this IQueryable<T> source, IFopRequest request)
{
int totalRowsAfterFiltering = source.Count();
// Filter
if (request.FilterList != null && request.FilterList.Any())
{
var whereExpression = string.Empty;
var enumTypes = new List<KeyValuePair<string, string>>();
for (var i = 0; i < request.FilterList.Count(); i++)
{
var filterList = request.FilterList.ToArray()[i];
(string generatedWhereExpression, List<KeyValuePair<string, string>> generatedEnumTypes) = GenerateDynamicWhereExpression(source, filterList);
whereExpression += generatedWhereExpression;
enumTypes.AddRange(generatedEnumTypes);
if (i < request.FilterList.Count() - 1)
{
whereExpression += ConvertLogicSyntax(FilterLogic.Or);
}
}
var interpreter = new Interpreter().Enablereplacedignment(replacedignmentOperators.None);
foreach (var enumType in enumTypes)
{
var t = Type.GetType($"{enumType.Key}, {enumType.Value}");
interpreter.Reference(t);
}
var expression = interpreter.ParseAsExpression<Func<T, bool>>(whereExpression, typeof(T).Name);
source = source.Where(expression);
totalRowsAfterFiltering = source.Count();
}
// Order
if (!string.IsNullOrEmpty(request.OrderBy))
{
source = source.OrderBy(request.OrderBy + " " + request.Direction);
}
// Paging
if (request.PageNumber > 0 && request.PageSize > 0)
{
source = source.Skip(request.PageSize * (request.PageNumber - 1)).Take(request.PageSize);
}
return (source, totalRowsAfterFiltering);
}
19
View Source File : TestOrderer.cs
License : Apache License 2.0
Project Creator : Asesjix
License : Apache License 2.0
Project Creator : Asesjix
public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases)
where TTestCase : ITestCase
{
return testCases
.OrderBy(t => t.GetOrder());
}
19
View Source File : ChildProcessTest_EnvironmentVariables.cs
License : MIT License
Project Creator : asmichi
License : MIT License
Project Creator : asmichi
private static void replacedertEnvironmentVariables(
IEnumerable<KV> expected,
ChildProcessCreationContext? context,
KV[] extraEnvVars,
bool inheritFromContext)
{
var actual = ExecuteForEnvironmentVariables(context, extraEnvVars, inheritFromContext);
var orderedExpected = expected.OrderBy(x => x, EnvironmentVariablePairNameComparer.DefaultThenOrdinal).ToArray();
if (!orderedExpected.SequenceEqual(actual))
{
// To diagnose environment-dependent issues, print all environment variables.
var message =
$"Expected: {ToString(orderedExpected)}\n" +
$"Actual: {ToString(actual)}";
throw new XunitException(message);
}
static string ToString(KV[] kvs) => "[" + string.Join(", ", kvs.Select(x => $"{x.Key}={x.Value}")) + "]";
}
19
View Source File : TestChildProgram.cs
License : MIT License
Project Creator : asmichi
License : MIT License
Project Creator : asmichi
private static int CommandDumpEnvironmentVariables()
{
// Output in UTF-8 so that the output will not be affected by the current code page.
using var sw = new StreamWriter(Console.OpenStandardOutput(), Encoding.UTF8);
var envVars = Environment.GetEnvironmentVariables();
foreach (var key in envVars.Keys.Cast<string>().OrderBy(x => x, StringComparer.Ordinal))
{
sw.Write("{0}={1}\0", key, (string?)envVars[key]);
}
return 0;
}
19
View Source File : SpecificationEvaluator.cs
License : MIT License
Project Creator : aspnetrun
License : MIT License
Project Creator : aspnetrun
public static IQueryable<T> GetQuery(IQueryable<T> inputQuery, ISpecification<T> specification)
{
var query = inputQuery;
// modify the IQueryable using the specification's criteria expression
if (specification.Criteria != null)
{
query = query.Where(specification.Criteria);
}
// Includes all expression-based includes
query = specification.Includes.Aggregate(query,
(current, include) => current.Include(include));
// Include any string-based include statements
query = specification.IncludeStrings.Aggregate(query,
(current, include) => current.Include(include));
// Apply ordering if expressions are set
if (specification.OrderBy != null)
{
query = query.OrderBy(specification.OrderBy);
}
else if (specification.OrderByDescending != null)
{
query = query.OrderByDescending(specification.OrderByDescending);
}
// Apply paging if enabled
if (specification.isPagingEnabled)
{
query = query.Skip(specification.Skip)
.Take(specification.Take);
}
return query;
}
19
View Source File : SpecificationEvaluator.cs
License : MIT License
Project Creator : aspnetrun
License : MIT License
Project Creator : aspnetrun
public static IQueryable<T> GetQuery(IQueryable<T> inputQuery, ISpecification<T> specification)
{
var query = inputQuery;
// modify the IQueryable using the specification's criteria expression
if (specification.Criteria != null)
{
query = query.Where(specification.Criteria);
}
// Includes all expression-based includes
query = specification.Includes.Aggregate(query, (current, include) => current.Include(include));
// Include any string-based include statements
query = specification.IncludeStrings.Aggregate(query, (current, include) => current.Include(include));
// Apply ordering if expressions are set
if (specification.OrderBy != null)
{
query = query.OrderBy(specification.OrderBy);
}
else if (specification.OrderByDescending != null)
{
query = query.OrderByDescending(specification.OrderByDescending);
}
// Apply paging if enabled
if (specification.isPagingEnabled)
{
query = query.Skip(specification.Skip)
.Take(specification.Take);
}
return query;
}
19
View Source File : MqttRouteTableFactory.cs
License : MIT License
Project Creator : Atlas-LiftTech
License : MIT License
Project Creator : Atlas-LiftTech
internal static MqttRouteTable Create(Dictionary<MethodInfo, string[]> templatesByHandler)
{
var routes = new List<MqttRoute>();
foreach (var keyValuePair in templatesByHandler)
{
var parsedTemplates = keyValuePair.Value.Select(v => TemplateParser.ParseTemplate(v)).ToArray();
var allRouteParameterNames = parsedTemplates
.SelectMany(GetParameterNames)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
foreach (var parsedTemplate in parsedTemplates)
{
var unusedRouteParameterNames = allRouteParameterNames
.Except(GetParameterNames(parsedTemplate), StringComparer.OrdinalIgnoreCase)
.ToArray();
var entry = new MqttRoute(parsedTemplate, keyValuePair.Key, unusedRouteParameterNames);
routes.Add(entry);
}
}
return new MqttRouteTable(routes.OrderBy(id => id, RoutePrecedence).ToArray());
}
19
View Source File : Node.cs
License : GNU Lesser General Public License v3.0
Project Creator : autocore-ai
License : GNU Lesser General Public License v3.0
Project Creator : autocore-ai
private void OnSceneGUI()
{
Tools.current = Tool.None;
if (Targets.Count > 0 && Targets.Count < maxMultiEditorCount)
{
Node movingNode = null;
foreach (var item in Targets)
{
var pos = Handles.PositionHandle(item.Position, item.transform.rotation);
if (!pos.Equals(item.Position))
{
movingNode = item;
pos.y = Utils.GetHeight(pos);
movingNode.Position = pos;
}
}
if (Targets.Count > 1 && movingNode)
{
var nearestNode = Targets.OrderBy(_ => Vector3.Distance(movingNode.Position, _.Position)).ElementAt(1);
if (Vector3.Distance(nearestNode.Position, movingNode.Position) < attachDistance)
{
movingNode.Merge(nearestNode);
}
}
}
}
See More Examples