public static ISet<int> GetSchemaVersionsForSubscription(List<string> capabilities) { //The first two schema versions follow the old regex, and versions 3 on follow the new one. if (capabilities == null) { throw new ArgumentNullException("capabilities"); } var matchesOld = capabilities.Select(s => ClustersContractCapabilityRegexOld.Match(s)).Where(match => match.Success).ToList(); var schemaVersions = new HashSet<int>(matchesOld.Select(m => Int32.Parse(m.Groups[1].Value, CultureInfo.CurrentCulture)).ToList()); var matchesNew = capabilities.Select(s => ClustersContractCapabilityRegex.Match(s)).Where(match => match.Success).ToList(); if (matchesNew.Count != 0) { schemaVersions.UnionWith( matchesNew.Select(m => Int32.Parse(m.Groups[1].Value, CultureInfo.CurrentCulture))); } if (schemaVersions == null || !schemaVersions.Any()) { throw new NotSupportedException("This subscription is not enabled for the clusters contract."); } return schemaVersions; }
public static void ApplySetPieces(World world) { var map = world.Map; int w = map.Width, h = map.Height; Random rand = new Random(); HashSet<Rect> rects = new HashSet<Rect>(); foreach (var dat in setPieces) { int size = dat.Item1.Size; int count = rand.Next(dat.Item2, dat.Item3); for (int i = 0; i < count; i++) { IntPoint pt = new IntPoint(); Rect rect; int max = 50; do { pt.X = rand.Next(0, w); pt.Y = rand.Next(0, h); rect = new Rect() { x = pt.X, y = pt.Y, w = size, h = size }; max--; } while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 || rects.Any(_ => Rect.Intersects(rect, _))) && max > 0); if (max <= 0) continue; dat.Item1.RenderSetPiece(world, pt); rects.Add(rect); } } }
public PathData pathTo(Pos target, Pos currentLocation, Tile[][] board, int spikeCost = 5) { Dictionary<string, InternalTile> Navigated = new Dictionary<string, InternalTile>(); HashSet<InternalTile> Closed = new HashSet<InternalTile>(); InternalTile beginning = new InternalTile() { TilePos = currentLocation, Weight = 0 }; HashSet<InternalTile> Opened = new HashSet<InternalTile> { beginning }; Dictionary<string, int> Scores = new Dictionary<string, int> { {GetKey(beginning.TilePos.x, beginning.TilePos.y), beginning.Weight} }; Dictionary<string, float> FullScores = new Dictionary<string, float> { {GetKey(beginning.TilePos.x, beginning.TilePos.y), GetDistance(currentLocation, target)} }; while (Opened.Any()) { InternalTile lowest = Opened.First(tile => GetKey(tile.TilePos.x, tile.TilePos.y) == GetLowestCostTile(FullScores, Opened)); if (lowest.TilePos.x == target.x && lowest.TilePos.y == target.y) { return ReconstructPath(Navigated, target); } Opened.Remove(lowest); Closed.Add(lowest); foreach (Pos neighbor in GetNeighbors(lowest.TilePos, board.Length, board[0].Length)) { if (Closed.Any(tile => tile.TilePos.x == neighbor.x && tile.TilePos.y == neighbor.y)) { continue; } string neighborKey = GetKey(neighbor.x, neighbor.y); int curScore = Scores[GetKey(lowest.TilePos.x, lowest.TilePos.y)] + 1; if (!Opened.Any(tile => tile.TilePos.x == neighbor.x && tile.TilePos.y == neighbor.y)) { Opened.Add(new InternalTile { TilePos = new Pos { x = neighbor.x, y = neighbor.y } }); } else if (curScore >= (Scores.ContainsKey(neighborKey) ? Scores[neighborKey] : int.MaxValue)) { continue; } Navigated.Add(neighborKey, lowest); Scores.Add(neighborKey, curScore); FullScores.Add(neighborKey, curScore + GetDistance(neighbor, target)); } } return null; }
/// <summary> /// Business or validation rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { var commands = (ProcessCommandEditList)context.InputPropertyValues[PrimaryProperty]; if (commands == null) return; foreach (var command in commands) { var foundConfigurations = new HashSet<ProcessCommandSecurityConfigurationEdit>(); var command1 = command; foreach (var configuration in command.SecurityConfigurationList.Where(configuration => !foundConfigurations.Any(f => f.RoleId == configuration.RoleId && f.StateGuid == configuration.StateGuid && f.BusinessUnitId == configuration.BusinessUnitId && f.PersonFieldSystemName == configuration.PersonFieldSystemName) && command1.SecurityConfigurationList.Any(x => !x.Equals(configuration) && x.RoleId == configuration.RoleId && x.StateGuid == configuration.StateGuid && x.BusinessUnitId == configuration.BusinessUnitId && x.PersonFieldSystemName == configuration.PersonFieldSystemName)) ) { foundConfigurations.Add(configuration); context.AddErrorResult(PrimaryProperty, string.Format(LanguageService.Translate("Rule_UniqueSecurityConfiguration"), command.CommandName)); } } }
public static bool CreatesNewLife(this Cell cell, ISet<Cell> cells, out ISet<Cell> newLife) { var emptyNeighbors = cellTransform.Select(t => cell + t).Where(c => !cells.Contains(c)); newLife = new HashSet<Cell>(emptyNeighbors.Where(n => GetNeighbors(n, cells).Count() == 3)); return newLife.Any(); }
public void CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services) { var types = codeUnit.Namespaces[0].Types; var attributes = new HashSet<string>(); foreach (var type in types.Cast<CodeTypeDeclaration>(). Where(type => type.IsClass && !type.IsContextType())) { attributes.Clear(); var @struct = new CodeTypeDeclaration { Name = AttributeConstsStructName, IsStruct = true, TypeAttributes = TypeAttributes.Public }; foreach (var member in from CodeTypeMember member in type.Members let prop = member as CodeMemberProperty where prop != null select prop) { CreateAttributeConstForProperty(@struct, member, attributes); } if (attributes.Any()) { type.Members.Insert(0, GenerateTypeWithoutEmptyLines(@struct)); } } }
public static ClaimsIdentity ToIdentity(this User user, string defaultProjectId = null) { if (user == null) return WindowsIdentity.GetAnonymous(); var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.EmailAddress), new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(OrganizationIdsClaim, String.Join(",", user.OrganizationIds.ToArray())) }; if (!String.IsNullOrEmpty(defaultProjectId)) claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId)); var userRoles = new HashSet<string>(user.Roles.ToArray()); if (userRoles.Any()) { // add implied scopes if (userRoles.Contains(AuthorizationRoles.GlobalAdmin)) userRoles.Add(AuthorizationRoles.User); if (userRoles.Contains(AuthorizationRoles.User)) userRoles.Add(AuthorizationRoles.Client); claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope))); } else { claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client)); claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User)); } return new ClaimsIdentity(claims, UserAuthenticationType); }
public iOSViewSource(HorizontalListView element, HashSet <DataTemplate> dataTemplates) { _weakElement = new WeakReference <HorizontalListView>(element); _createdCells = new Dictionary <long, WeakReference <iOSViewCell> >(); _dataTemplates = dataTemplates; var elementItemsSource = element.ItemsSource; _dataSource = elementItemsSource?.Cast <object>().ToList(); if (_dataSource == null) { return; } _multipleCellTemplates = _dataTemplates?.Any() ?? false; if (!_multipleCellTemplates) { // Cache only support single DataTemplate _viewCellHolderCellHolderQueue = new UIViewCellHolderQueue( element.ViewCacheSize, () => CreateViewCellHolder()); _viewCellHolderCellHolderQueue.Build(); } }
private static void FindIndirectCircularReferences(ISet<Node> childList) { var toIgnore = new HashSet<Node>(); foreach (var node in childList.ToHashSet()) { if(toIgnore.Contains(node)) continue; var path = new HashSet<Node>(); if (IndirectlyDependsOnItself(node, node, ref path)) { path.Add(node); toIgnore.UnionWith(path); childList.ExceptWith(path); var dependantOnCircularDependencies = childList.Where(x => path.Any(x.DependsOn)); var cirularHolder = new CircularDependencyHolderNode(path); foreach (var dependantOnCircularDependency in dependantOnCircularDependencies) { //Remove all dependencies on nodes in the path dependantOnCircularDependency.SiblingDependencies.RemoveWhere(x => path.Contains(x)); //Add dependency on circular holder dependantOnCircularDependency.SiblingDependencies.Add(cirularHolder); } //Add all dependencies in the path to the new node cirularHolder.SiblingDependencies.UnionWith(path.SiblingDependencies().Except(path)); //Should not be dependant on themselves childList.Add(cirularHolder); } } }
private void OutputReferences(Output result, DependencyGraph graph, Library lib, string type) { result.AppendLine(GetName(lib) + ":"); var directDeps = new HashSet<Library>(graph.OutEdges(lib) .Select(d => d.Target)); result.IncreaseIndent(); result.AppendLine("Direct " + type + ":"); result.IncreaseIndent(); Output(result, directDeps); result.DecreaseIndent(); result.DecreaseIndent(); if (directDeps.Any()) { var indirectDeps = ComputeIndirectDeps(graph, lib) .Where(d => !directDeps.Contains(d)) // ReSharper disable once PossibleUnintendedReferenceComparison .Where(d => d != lib); result.IncreaseIndent(); result.AppendLine("Indirect " + type + ":"); result.IncreaseIndent(); Output(result, indirectDeps); result.DecreaseIndent(); result.DecreaseIndent(); } result.AppendLine(); }
public static IEnumerable<SyntaxNode> GetUnnecessaryImports(SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken) { var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken); if (!diagnostics.Any()) { return null; } var unnecessaryImports = new HashSet<UsingDirectiveSyntax>(); foreach (var diagnostic in diagnostics) { if (diagnostic.Id == "CS8019") { var node = root.FindNode(diagnostic.Location.SourceSpan) as UsingDirectiveSyntax; if (node != null) { unnecessaryImports.Add(node); } } } if (cancellationToken.IsCancellationRequested || !unnecessaryImports.Any()) { return null; } return unnecessaryImports; }
protected override void ProcessPackage(PackageProvider provider, IEnumerable<string> searchKey, SoftwareIdentity package) { try { base.ProcessPackage(provider, searchKey, package); // return the object to the caller now. WriteObject(package); if (IncludeDependencies) { var missingDependencies = new HashSet<string>(); foreach (var dep in package.Dependencies) { // note: future work may be needed if the package sources currently selected by the user don't // contain the dependencies. var dependendcies = PackageManagementService.FindPackageByCanonicalId(dep, this); var depPkg = dependendcies.OrderByDescending(pp => pp, SoftwareIdentityVersionComparer.Instance).FirstOrDefault(); if (depPkg == null) { missingDependencies.Add(dep); Warning(Constants.Messages.UnableToFindDependencyPackage, dep); } else { ProcessPackage(depPkg.Provider, searchKey.Select(each => each + depPkg.Name).ToArray(), depPkg); } } if (missingDependencies.Any()) { Error(Constants.Errors.UnableToFindDependencyPackage, missingDependencies.JoinWithComma()); } } } catch (Exception ex) { Debug("Calling ProcessPackage {0}", ex.ToString()); } }
public static ClaimsIdentity CreateUserIdentity(string emailAddress, string id, string[] organizationIds, string[] roles, string defaultProjectId = null) { var claims = new List<Claim> { new Claim(ClaimTypes.Name, emailAddress), new Claim(ClaimTypes.NameIdentifier, id), new Claim(OrganizationIdsClaim, String.Join(",", organizationIds)) }; if (!String.IsNullOrEmpty(defaultProjectId)) claims.Add(new Claim(DefaultProjectIdClaim, defaultProjectId)); var userRoles = new HashSet<string>(roles); if (userRoles.Any()) { // add implied scopes if (userRoles.Contains(AuthorizationRoles.GlobalAdmin)) userRoles.Add(AuthorizationRoles.User); if (userRoles.Contains(AuthorizationRoles.User)) userRoles.Add(AuthorizationRoles.Client); claims.AddRange(userRoles.Select(scope => new Claim(ClaimTypes.Role, scope))); } else { claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.Client)); claims.Add(new Claim(ClaimTypes.Role, AuthorizationRoles.User)); } return new ClaimsIdentity(claims, UserAuthenticationType); }
public async Task<IEnumerable<UserData>> Post(IEnumerable<ScoreData> scores, string p) { if (p != ConfigurationManager.AppSettings["SyncPass"]) return null; var users = (await _userDataRepo.Get()).ToDictionary(x => x.UserId, x => x); var usersToUpdate = new HashSet<UserData>(); foreach (var score in scores) { UserData user; if (users.ContainsKey(score.UserId)) { user = users[score.UserId]; } else { user = new UserData { UserId = score.UserId }; users.Add(score.UserId, user); usersToUpdate.Add(user); } if (user.Score != score.Score) { user.Score = score.Score; usersToUpdate.Add(user); } } if (usersToUpdate.Any()) await _userDataRepo.SaveBatch(usersToUpdate); return users.Values; }
public int[] FindBest() { var remaining = new HashSet<Point>(_cities); var first = remaining.First(); var route = new List<Point> { first }; remaining.Remove(first); var numericRoute = new List<int>{_cities.IndexOf(first)}; var distance = 0.0d; while (remaining.Any()) { var shortest = double.MaxValue; Point next = null; foreach (var p in remaining) { var d = Distance(route.Last(), p); if (d < shortest) { shortest = d; next = p; } } route.Add(next); numericRoute.Add(_cities.IndexOf(next)); remaining.Remove(next); distance += shortest; } distance += Distance(route.First(), route.Last()); Console.WriteLine("Distance calculated in closestneighbour: " + distance); return numericRoute.ToArray(); }
public void Render(IGraphNode<LibraryDependency> root) { // tuples of <Library Name, Requested Version, Actual Version> var results = new HashSet<Tuple<string, string, string>>(); root.DepthFirstPreOrderWalk( (node, ancestors) => { var dependency = node.Item; if (IsLibraryMismatch(dependency)) { results.Add(Tuple.Create( dependency.Library.Identity.Name, dependency.LibraryRange.VersionRange?.MinVersion.ToString(), dependency.Library.Identity.Version?.ToString())); } return true; }); if (results.Any()) { var format = GetFormat(results, padding: 2); RenderTitle(format); RenderMismatches(format, results); } }
public override void Generate() { Console.WriteLine("Generating Age ranges"); var uniqueAgeRanges = new HashSet<AgeRanx>(); while (uniqueAgeRanges.Count != this.Count) { var minAge = this.Random.GetInt(0, 20); var maxAge = minAge + this.Random.GetInt(1, 5); var newAgeRange = new AgeRanx { MaxAge = maxAge, MinAge = minAge }; if (!uniqueAgeRanges.Any(a => a.MinAge == minAge && a.MaxAge == maxAge)) { uniqueAgeRanges.Add(newAgeRange); } } var index = 0; foreach (var uniqueAgeRange in uniqueAgeRanges) { Db.AgeRanges.Add(uniqueAgeRange); index++; if (index % 100 == 0) { Console.Write("."); Db.SaveChanges(); } } Console.WriteLine("\nGenerating Age Ranges Done!"); }
public static void Extents(Ytyp[] ytypfiles, Ymap[] ymapfiles) { List <CBaseArchetypeDef> archetypeList = null; if (ytypfiles != null && ytypfiles.Length != 0) { archetypeList = Ytyp.Merge(ytypfiles).CMapTypes.archetypes; } if (ymapfiles != null && ymapfiles.Length != 0) { for (int i = 0; i < ymapfiles.Length; i++) { HashSet <string> missing = ymapfiles[i].UpdateExtents(archetypeList); if (missing?.Any() ?? false) { foreach (string name in missing) { Console.WriteLine("Missing CBaseArchetypeDef: " + name); } } ymapfiles[i].WriteXML().Save(ymapfiles[i].filename); Console.WriteLine("Updated extents for " + ymapfiles[i].filename); } } }
public IEnumerable<State> TransitiveClosure ( Func<SimpleTransition, bool> selector, Func<SimpleTransition, bool> cancel) { var done = new HashSet<State> (); var work = new HashSet<State> (); work.Add (this); while (work.Any ()) { var q = work.First (); work.Remove (q); done.Add (q); if (q.Delta == null) { continue; } var ts = q.Delta .Where (t => selector == null || selector (t)) .ToArray (); if (cancel != null && ts.Any (cancel)) { return null; } foreach (var qn in ts.Select (t => t.Next)) { if (!done.Contains (qn)) { work.Add (qn); } } } return done; }
private static void Main() { var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); var n = input[0]; var coord0 = new Coord(input[1], input[2]); var rgcoord = new HashSet<Coord>(); for (var i = 0; i < n; i++) { input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); rgcoord.Add(new Coord(input[0], input[1])); } var d = 0; while (rgcoord.Any()) { d++; var coord = rgcoord.First(); var vX = coord.x - coord0.x; var vY = coord.y - coord0.y; foreach (var coordT in rgcoord.ToList()) { if (vY*(coordT.x - coord0.x) == vX*(coordT.y - coord0.y)) rgcoord.Remove(coordT); } } Console.WriteLine(d); }
public static IEnumerable<string> GetJarsFromPOM(this IMavenArtifactHandler handler, MavenPartialPOM pom) { if (handler == null) { throw new ArgumentNullException("handler"); } if (pom == null) { throw new ArgumentNullException("pom"); } ISet<string> jarFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (MavenDependency dependency in pom.Dependencies) { string jarFilePath = handler.FetchArtifactJarFile(dependency); if (jarFilePath != null) { Debug.Assert(!jarFilePaths.Contains(jarFilePath, StringComparer.OrdinalIgnoreCase), "Expecting full jar paths to be unique"); Debug.Assert(!jarFilePaths.Any(j => Path.GetFileName(j).Equals(Path.GetFileName(jarFilePath), StringComparison.OrdinalIgnoreCase)), "Expecting jars file names to be unique"); jarFilePaths.Add(jarFilePath); } } return jarFilePaths; }
public void all_events_are_checked() { var eventAssembly = typeof (CreditCourseCreatedEvent).Assembly; var testAssembly = Assembly.GetExecutingAssembly(); var eventTypes = eventAssembly.GetTypes() .Where(t => t.IsClass && !t.IsAbstract && typeof (IEvent).IsAssignableFrom(t)); var eventFixtureTypes = testAssembly.GetTypes() .Where(t => t.IsClass && !t.IsAbstract); var missingTests = new HashSet<Type>(); foreach (var eventType in eventTypes) { var fixtureBaseType = typeof (EventSerializationFixture<>) .MakeGenericType(eventType); var fixtureTypes = eventFixtureTypes .Where(t => fixtureBaseType.IsAssignableFrom(t)) .ToArray(); if (!fixtureTypes.Any()) missingTests.Add(eventType); } if (missingTests.Any()) Assert.Fail("The following events are not being tested: {0}", string.Join(Environment.NewLine, missingTests)); }
static int Main(string[] args) { var commandArguments = CommandArguments.Parse(args); if (!string.IsNullOrEmpty(commandArguments.Error)) { Console.WriteLine(commandArguments.Error); return -1; } var returnCode = 0; var options = commandArguments.ParsedOptions; var modelsToProcess = new HashSet<string>(StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(options.ServiceModels)) { foreach (var s in options.ServiceModels.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { modelsToProcess.Add(s); } } try { if (options.CompileCustomizations) // Compile all servicename.customizations*.json files into one json file in bin CustomizationCompiler.CompileServiceCustomizations(options.ModelsFolder); var generationManifest = GenerationManifest.Load(options.Manifest, options.Versions, options.ModelsFolder); foreach (var serviceConfig in generationManifest.ServiceConfigurations) { if (modelsToProcess.Any() && !modelsToProcess.Contains(serviceConfig.ModelName)) { Console.WriteLine("Skipping model (not in -servicemodels set to process): {0} ({1})", serviceConfig.ModelName, serviceConfig.ModelPath); continue; } Console.WriteLine("Processing model: {0} ({1})", serviceConfig.ModelName, serviceConfig.ModelPath); var driver = new GeneratorDriver(serviceConfig, generationManifest, options); driver.Execute(); } GeneratorDriver.UpdateSolutionFiles(options); GeneratorDriver.UpdateAssemblyVersionInfo(generationManifest, options); GeneratorDriver.UpdateUnitTestProjectReferences(options); } catch (Exception e) { Console.Error.WriteLine("Error running generator: " + e.Message); Console.Error.WriteLine(e.StackTrace); returnCode = -1; } if (options.WaitOnExit) { Console.WriteLine(); Console.WriteLine("Generation complete. Press a key to exit."); Console.ReadLine(); } return returnCode; }
public IEnumerable<int> Parse(string message) { var lexer = new StringCalculatorLexer(message); var delimiters = new HashSet<string>(); string numbersString = null; foreach (var token in lexer.Read()) { if (token is DelimiterToken) { delimiters.Add(token.Content); } if (token is NumbersToken) { numbersString = token.Content; } } if (string.IsNullOrEmpty(numbersString)) { return Enumerable.Empty<int>(); } var numberSplitter = delimiters.Any() ? delimiters.GenerateSplitter() : _defaultSplitter; return numberSplitter .Split(numbersString) .Select(int.Parse); }
public long GetNextAvailableLong(List<long> values, bool returnZero) { if (values == null || !values.Any()) { if (returnZero) { return 0; } else { return 1; } } HashSet<long> hashSetValues = new HashSet<long>(values); long x = hashSetValues.Min(); while (hashSetValues.Any(m => m == x)) { x++; if (x == 0 && !returnZero) { x++; } } return x; }
public override QState Initialize() { WriteOutput("Dimensions: " + width + "x" + height); self = new Point(start.X, start.Y); score = 0; walls = new Point[] { }; // Generate Walls Randomly if (wallDensity > 0) { HashSet<Point> bestPathSoFar = new HashSet<Point>(); WriteOutput("Generating walls randomly with density target of " + wallDensity + "..."); for (int w = 0; w < width; w++) { for (int h = 0; h < height; h++) { double r = random.NextDouble(); //WriteOutput("Wall Probability for " + w + "x" + h + ": " + r+" vs threshold "+walls); if (r < wallDensity) { //WriteOutput("Wall created at " + w + "x" + h); Point newWall = new Point(w, h); if (start == newWall || goal == newWall) continue; Point[] tempWalls = walls.Concat(new Point[] { newWall }).ToArray(); QState tempState = new Maze() { maze = maze, self = self, goal = goal, width = width, height = height, walls = tempWalls}; if (!bestPathSoFar.Any() || bestPathSoFar.Contains(newWall)) { QSearchResult path = new QSearch().AStar(tempState); if (path != null) { bestPathSoFar.Clear(); foreach (QState q in path.QStatesList) bestPathSoFar.Add(((Maze)q).self); walls = tempWalls; } } else walls = tempWalls; } } } WriteOutput("Maze generation complete."); } opponent = new List<Point>(); for (int i = 0; i < opponents; i++) opponent.Add(new Point(goal.X, goal.Y)); if (!HideOutput) { ManualResetEvent wait = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback(CreateGUI), new object[] { width, height, self.X, self.Y, goal.X, goal.Y, walls, this, wait }); wait.WaitOne(); } return new Maze() { width = width, height = height, self = self, goal = goal, walls = walls, wallDensity = wallDensity, opponent = opponent, opponentDifficulty = opponentDifficulty, random = random, maze = maze, start = start, opponents = opponents, bestOpponentPath = bestOpponentPath, score = score }; }
/// <summary> /// When the tessellated solid is sliced at the specified plane, the contact surfaces are /// described by the return ContactData object. This is a non-destructive function typically /// used to find the shape and size of 2D surface on the prescribed plane.. /// </summary> /// <param name="plane">The plane.</param> /// <param name="ts">The ts.</param> /// <returns>ContactData.</returns> /// <exception cref="System.Exception">Contact Edges found that are not contained in loop.</exception> public static ContactData DefineContact(Flat plane, TessellatedSolid ts) { var vertexDistancesToPlane = new double[ts.NumberOfVertices]; for (int i = 0; i < ts.NumberOfVertices; i++) vertexDistancesToPlane[i] = ts.Vertices[i].Position.dotProduct(plane.Normal) - plane.DistanceToOrigin; // the edges serve as the easiest way to identify where the solid is interacting with the plane. // Instead of a foreach, the while loop lets us look ahead to known edges that are irrelevant. var edgeHashSet = new HashSet<Edge>(ts.Edges); // Contact elements are constructed and then later arranged into loops. Loops make up the returned object, ContactData. var straddleContactElts = new List<ContactElement>(); var inPlaneContactElts = new List<CoincidentEdgeContactElement>(); while (edgeHashSet.Any()) { // instead of the foreach, we have this while statement and these first 2 lines to enumerate over the edges. var edge = edgeHashSet.First(); edgeHashSet.Remove(edge); var toDistance = vertexDistancesToPlane[edge.To.IndexInList]; var fromDistance = vertexDistancesToPlane[edge.From.IndexInList]; if (StarMath.IsNegligible(toDistance) && StarMath.IsNegligible(fromDistance)) ContactElement.MakeInPlaneContactElement(plane, edge, edgeHashSet, vertexDistancesToPlane, inPlaneContactElts); else if ((toDistance > 0 && fromDistance < 0) || (toDistance < 0 && fromDistance > 0)) straddleContactElts.Add(new ThroughFaceContactElement(plane, edge, toDistance)); } foreach (var contactElement in inPlaneContactElts) { // next, we find any additional vertices that just touch the plane but don't have in-plane edges // to facilitate this we negate all vertices already captures in the inPlaneContactElts vertexDistancesToPlane[contactElement.StartVertex.IndexInList] = double.NaN; vertexDistancesToPlane[contactElement.EndVertex.IndexInList] = double.NaN; } for (int i = 0; i < ts.NumberOfVertices; i++) { if (!StarMath.IsNegligible(vertexDistancesToPlane[i])) continue; var v = ts.Vertices[i]; PolygonalFace negativeFace, positiveFace; if (ThroughVertexContactElement.FindNegativeAndPositiveFaces(plane, v, vertexDistancesToPlane, out negativeFace, out positiveFace)) straddleContactElts.Add(new ThroughVertexContactElement(v, negativeFace, positiveFace)); } straddleContactElts.AddRange(inPlaneContactElts); var loops = new List<Loop>(); var numberOfTries = 0; while (straddleContactElts.Any() && numberOfTries < straddleContactElts.Count) { // now build loops from stringing together contact elements var loop = FindLoop(plane, straddleContactElts, vertexDistancesToPlane); if (loop != null) { Debug.WriteLine(loops.Count + ": " + loop.MakeDebugContactString() + " "); loops.Add(loop); numberOfTries = 0; } else numberOfTries++; } if (straddleContactElts.Any()) Debug.WriteLine("Contact Edges found that are not contained in loop."); return new ContactData(loops); }
public void HashSetExtensions_AnyWithPredicate_ReturnsTrueIfHashSetContainsMatchingItems() { var set = new HashSet<Int32>() { 1, 2, 3 }; var result = set.Any(x => x % 2 == 0); TheResultingValue(result).ShouldBe(true); }
public void HashSetExtensions_Any_ReturnsTrueIfHashSetContainsItems() { var set = new HashSet<Int32>() { 1 }; var result = set.Any(); TheResultingValue(result).ShouldBe(true); }
public void HashSetExtensions_Any_ReturnsFalseIfHashSetDoesNotContainItems() { var set = new HashSet<Int32>(); var result = set.Any(); TheResultingValue(result).ShouldBe(false); }
public string ValidateFile(string pathToFile) { try { var doc = XDocument.Load(pathToFile); var root = doc.Root; if (root.Name.LocalName != SharedConstants.AdditionalFieldsTag) return "Not valid custom properties file"; if (!root.HasElements) return null; // CustomFields are optional. var requiredAttrs = new HashSet<string> { "name", "class", "type", Key // Special attr added so fast xml splitter can find each one. }; var optionalAttrs = new HashSet<string> { "destclass", "wsSelector", "helpString", "listRoot", "label" }; foreach (var customFieldElement in root.Elements(SharedConstants.CustomField)) { if (requiredAttrs .Any(requiredAttr => customFieldElement.Attribute(requiredAttr) == null)) { return "Missing required custom property attribute"; } if (customFieldElement.Attributes() .Any(attribute => !requiredAttrs.Contains(attribute.Name.LocalName) && !optionalAttrs.Contains(attribute.Name.LocalName))) { return "Contains unrecognized attribute"; } // Make sure 'key' attr is class+name. if (customFieldElement.Attribute("class").Value + customFieldElement.Attribute("name").Value != customFieldElement.Attribute(Key).Value) return "Mis-matched 'key' attribute with property class+name atributes"; if (customFieldElement.HasElements) return "Contains illegal child element"; } MetadataCache.MdCache.AddCustomPropInfo(new MergeOrder( pathToFile, pathToFile, pathToFile, new MergeSituation(pathToFile, "", "", "", "", MergeOrder.ConflictHandlingModeChoices.WeWin))); return null; } catch (Exception e) { return e.Message; } }
public static void AssertLinesInclude(this DocumentAnalyzer actual, params LineSpan[] expected) { var missingLines = new HashSet<LineSpan>(expected).Except(actual.GetAllLines()); if (missingLines.Any()) { Assert.Fail("Lines not found:\r\n{0}\r\n\r\nActual lines:\r\n{1}", missingLines.ToFormattedString(), actual.GetAllLines().ToFormattedString()); } }
/// <summary> /// Determines whether the specified URL is reserved or is inside a reserved path. /// </summary> /// <param name="absPath">The Path of the URL to check.</param> /// <returns> /// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>. /// </returns> private bool IsReservedPathOrUrl(string absPath) { LazyInitializer.EnsureInitialized(ref _reservedList, ref _isInit, ref _initLocker, () => { // store references to strings to determine changes var reservedPathsCache = _globalSettings.ReservedPaths; var reservedUrlsCache = _globalSettings.ReservedUrls; // add URLs and paths to a new list var newReservedList = new HashSet <string>(); foreach (var reservedUrlTrimmed in NormalizePaths(reservedUrlsCache, false)) { newReservedList.Add(reservedUrlTrimmed); } foreach (var reservedPathTrimmed in NormalizePaths(reservedPathsCache, true)) { newReservedList.Add(reservedPathTrimmed); } // use the new list from now on return(newReservedList); }); // The URL should be cleaned up before checking: // * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/' // * We shouldn't be comparing the query at all if (absPath.Contains('?')) { absPath = absPath.Split('?', StringSplitOptions.RemoveEmptyEntries)[0]; } if (absPath.Contains('.') == false) { absPath = absPath.EnsureEndsWith('/'); } // return true if URL starts with an element of the reserved list var isReserved = _reservedList?.Any(x => absPath.InvariantStartsWith(x)) ?? false; if (isReserved) { return(true); } // If configured, check if the current request matches a route, if so then it is reserved, // else if not configured (default) proceed as normal since we assume the request is for an Umbraco content item. var hasRoute = _routingSettings.TryMatchingEndpointsForAllPages && _routeChecks.GetOrAdd(absPath, x => MatchesEndpoint(absPath)); if (hasRoute) { return(true); } return(false); }
/// <summary> /// Заполнение дерева репозиториями /// </summary> public void PopulateTreeByRepos(NodeFactory nodeFactory, HashSet <string> projectsToIgnoreKeys = null) { if (nodeFactory == null) { throw new ArgumentNullException(nameof(nodeFactory)); } var projects = _codebaseService.GetProjects(); if (projectsToIgnoreKeys?.Any() == true) { projects = projects.Where(p => !projectsToIgnoreKeys.Contains(p.Key)); } Tree.Clear(); foreach (var project in projects) { Tree.Add(nodeFactory.CreateNode( // Project node project, projectNode => { projectNode.Parent = null; projectNode.IsExpanded = true; projectNode.Nodes = new ObservableCollection <Node>( _codebaseService.GetRepos(project) .Select(repo => nodeFactory.CreateNode <RepoNode>( // Repo node repo, repoNode => { repoNode.Parent = projectNode; repoNode.IsExpanded = true; repoNode.CompareMode = CompareMode.ByChildren; }))); })); } }
private void BuildVehicleList(XPathNodeIterator objXmlVehicleList) { string strSpace = LanguageManager.GetString("String_Space"); int intOverLimit = 0; List <ListItem> lstVehicles = new List <ListItem>(); foreach (XPathNavigator objXmlVehicle in objXmlVehicleList) { if (chkHideOverAvailLimit.Checked && !objXmlVehicle.CheckAvailRestriction(_objCharacter)) { ++intOverLimit; continue; } if (!chkFreeItem.Checked && chkShowOnlyAffordItems.Checked) { decimal decCostMultiplier = 1.0m; if (chkUsedVehicle.Checked) { decCostMultiplier -= (nudUsedVehicleDiscount.Value / 100.0m); } decCostMultiplier *= 1 + (nudMarkup.Value / 100.0m); if (_setBlackMarketMaps.Contains(objXmlVehicle.SelectSingleNode("category")?.Value)) { decCostMultiplier *= 0.9m; } if (_setDealerConnectionMaps?.Any(set => objXmlVehicle.SelectSingleNode("category")?.Value.StartsWith(set, StringComparison.Ordinal) == true) == true) { decCostMultiplier *= 0.9m; } if (!objXmlVehicle.CheckNuyenRestriction(_objCharacter.Nuyen, decCostMultiplier)) { ++intOverLimit; continue; } } string strDisplayname = objXmlVehicle.SelectSingleNode("translate")?.Value ?? objXmlVehicle.SelectSingleNode("name")?.Value ?? LanguageManager.GetString("String_Unknown"); if (!GlobalOptions.SearchInCategoryOnly && txtSearch.TextLength != 0) { string strCategory = objXmlVehicle.SelectSingleNode("category")?.Value; if (!string.IsNullOrEmpty(strCategory)) { ListItem objFoundItem = _lstCategory.Find(objFind => objFind.Value.ToString() == strCategory); if (!string.IsNullOrEmpty(objFoundItem.Name)) { strDisplayname += strSpace + '[' + objFoundItem.Name + ']'; } } } lstVehicles.Add(new ListItem(objXmlVehicle.SelectSingleNode("id")?.Value ?? string.Empty, strDisplayname)); } lstVehicles.Sort(CompareListItems.CompareNames); if (intOverLimit > 0) { // Add after sort so that it's always at the end lstVehicles.Add(new ListItem(string.Empty, string.Format(GlobalOptions.CultureInfo, LanguageManager.GetString("String_RestrictedItemsHidden"), intOverLimit))); } string strOldSelected = lstVehicle.SelectedValue?.ToString(); _blnLoading = true; lstVehicle.BeginUpdate(); lstVehicle.ValueMember = nameof(ListItem.Value); lstVehicle.DisplayMember = nameof(ListItem.Name); lstVehicle.DataSource = lstVehicles; _blnLoading = false; if (string.IsNullOrEmpty(strOldSelected)) { lstVehicle.SelectedIndex = -1; } else { lstVehicle.SelectedValue = strOldSelected; } lstVehicle.EndUpdate(); }
public static void Create(BotClass bot) { var imp = new Impersonator(); try { if (bot.UseWindowsUser) { imp.Impersonate(bot.WindowsUserName, "localhost", bot.WindowsUserPassword); } bot.Status = "Create Diablo Clone"; var basepath = Path.GetDirectoryName(bot.Diablo.Location); var clonepath = Path.Combine(bot.DiabloCloneLocation, "Diablo III"); // if diablo base path does not exist stop here! if (basepath != null && !Directory.Exists(basepath)) { bot.Stop(); throw new Exception("Diablo base directory does not exist!"); } // Check if given language is installed on basepath var testpath = Path.Combine(basepath, @"Data_D3\PC\MPQs", General.GetLocale(bot.Diablo.Language)); if (!Directory.Exists(testpath)) { bot.Stop(); throw new Exception(string.Format("ERROR: {0} language is not installed (path: {1})", bot.Diablo.Language, testpath)); } // if diablo clone does not exist create it if (!Directory.Exists(Path.Combine(clonepath, @"Data_D3\PC\MPQs\Cache"))) { Logger.Instance.Write(bot, "Creating new Diablo Clone"); Directory.CreateDirectory(Path.Combine(clonepath, @"Data_D3\PC\MPQs\Cache")); } // Create Search caches var baseFileCache = new FileListCache(basepath); var cloneFileCache = new FileListCache(clonepath); // Check if all links are made for our clone foreach (var p in baseFileCache.FileList) { try { if (p.directory && !Directory.Exists(Path.Combine(clonepath.ToLower(), p.Path.ToLower()))) { if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path))) { Logger.Instance.Write(bot, "NewLink: {0} -> {1}", Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path)); //if (!CreateSymbolicLink( Path.Combine(clonepath,p.Path), Path.Combine(basepath,p.Path), 1)) // throw new Exception("Failed to create link!"); Directory.CreateDirectory(Path.Combine(clonepath, p.Path)); } continue; } if (!p.directory && !File.Exists(Path.Combine(clonepath.ToLower(), p.Path.ToLower()))) { if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path))) { Logger.Instance.Write(bot, "NewLink: {0} -> {1}", Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path)); if (Path.GetExtension(Path.Combine(clonepath, p.Path)).ToLower().Equals(".exe")) { if ( !CreateHardLink(Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path), IntPtr.Zero)) { throw new Exception("Failed to create link!"); } } else { if ( !CreateSymbolicLink(Path.Combine(clonepath, p.Path), Path.Combine(basepath, p.Path), 0)) { throw new Exception("Failed to create link!"); } } } } } catch (Exception ex) { Console.WriteLine(ex); } } // Remove links that have no target /* * foreach (var p in cloneFileCache.FileList) * { * try * { * if (p.directory && !Directory.Exists(Path.Combine(basepath, p.Path))) * { * if (!_noLinks.Any(n => General.WildcardMatch(n.Source.ToLower(), p.Path.ToLower()))) * Console.WriteLine("Delete: {0}", p.Path); * continue; * } * * if (!p.directory && !File.Exists(Path.Combine(basepath.ToLower(), p.Path.ToLower()))) * { * if (!_noLinks.Any(n => General.WildcardMatch(n.Source, p.Path))) * Console.WriteLine("Delete: {0}", p.Path); * } * } * catch (Exception ex) * { * Logger.Instance.Write(bot, ex.ToString()); * } * } */ } catch (Exception ex) { bot.Stop(); DebugHelper.Write(bot, "Failed to create clone!"); DebugHelper.Exception(ex); } imp.Dispose(); }
bool IsProductAlreadyInCart(ProductDetails product) => _cartItems?.Any(c => c.Product.Id == product.Id) ?? false;
CPos MeetupPoint(Actor self, HashSet <Actor> hash, CPos target) { ; if (!hash.Any()) { return(CPos.Zero); } var fromhere = hash.ElementAt(self.World.SharedRandom.Next(hash.Count)); HashSet <CPos> alllocations = new HashSet <CPos>(); foreach (var acto in hash) { if (acto != null && !acto.IsDead && acto.IsInWorld) { alllocations.Add(acto.Location); } } if (!alllocations.Any()) { return(CPos.Zero); } if (fromhere != null && !fromhere.IsDead && fromhere.IsInWorld && fromhere.Info.HasTraitInfo <MobileInfo>()) { var ip = fromhere.Info.TraitInfo <IPositionableInfo>(); var validcells = self.World.Map.FindTilesInCircle(target, 3, true).Where(c => ip.CanEnterCell(self.World, null, c)); var cPoses = validcells as CPos[] ?? validcells.ToArray(); if (!cPoses.Any()) { return(CPos.Zero); } var pickClosestCell = cPoses.MinByOrDefault(c => (self.World.Map.CenterOfCell(c) - fromhere.CenterPosition).LengthSquared); List <CPos> path; using (var thePath = PathSearch.FromPoint(self.World, fromhere.Info.TraitInfo <MobileInfo>(), self, fromhere.Location, pickClosestCell, true)) path = self.World.WorldActor.Trait <IPathFinder>().FindPath(thePath); if (path.Any()) { foreach (var loco in path) { var owner = self.Owner; var position = owner.World.Map.CenterOfCell(loco); var beacon = self.Owner.PlayerActor.Info.TraitInfo <PlaceBeaconInfo>(); var playerBeacon = new Beacon(self.Owner, position, 20 * 25, beacon.Palette, beacon.IsPlayerPalette, beacon.BeaconImage, beacon.ArrowSequence, beacon.CircleSequence); self.Owner.PlayerActor.World.AddFrameEndTask(w => w.Add(playerBeacon)); } if (path.Count > 11) { return(path.ElementAt(10)); } return(path.Last()); } } return(CPos.Zero); }
public IReadOnlyCollection <ScanResult> GetResult() { return(_results.Any() ? _results.ToArray() : new[] { ScanResult.Failure() }); }
private bool OnCollision(Fixture f1, Fixture f2, Contact contact) { if (User == null || User.Removed) { RestoreCollision(); hitting = false; User = null; } Character targetCharacter = null; Limb targetLimb = null; Structure targetStructure = null; attack?.SetUser(User); if (f2.Body.UserData is Limb) { targetLimb = (Limb)f2.Body.UserData; if (targetLimb.IsSevered || targetLimb.character == null) { return(false); } targetCharacter = targetLimb.character; if (targetCharacter == picker) { return(false); } if (AllowHitMultiple) { if (hitTargets.Contains(targetCharacter)) { return(false); } } else { if (hitTargets.Any(t => t is Character)) { return(false); } } hitTargets.Add(targetCharacter); } else if (f2.Body.UserData is Character) { targetCharacter = (Character)f2.Body.UserData; if (targetCharacter == picker) { return(false); } targetLimb = targetCharacter.AnimController.GetLimb(LimbType.Torso); //Otherwise armor can be bypassed in strange ways if (AllowHitMultiple) { if (hitTargets.Contains(targetCharacter)) { return(false); } } else { if (hitTargets.Any(t => t is Character)) { return(false); } } hitTargets.Add(targetCharacter); } else if (f2.Body.UserData is Structure) { targetStructure = (Structure)f2.Body.UserData; if (AllowHitMultiple) { if (hitTargets.Contains(targetStructure)) { return(true); } } else { if (hitTargets.Any(t => t is Structure)) { return(true); } } hitTargets.Add(targetStructure); } else { return(false); } if (attack != null) { if (targetLimb != null) { targetLimb.character.LastDamageSource = item; attack.DoDamageToLimb(User, targetLimb, item.WorldPosition, 1.0f); } else if (targetCharacter != null) { targetCharacter.LastDamageSource = item; attack.DoDamage(User, targetCharacter, item.WorldPosition, 1.0f); } else if (targetStructure != null) { attack.DoDamage(User, targetStructure, item.WorldPosition, 1.0f); } else { return(false); } } if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return(true); } #if SERVER if (GameMain.Server != null && targetCharacter != null) //TODO: Log structure hits { GameMain.Server.CreateEntityEvent(item, new object[] { Networking.NetEntityEvent.Type.ApplyStatusEffect, ActionType.OnUse, null, //itemcomponent targetCharacter.ID, targetLimb }); string logStr = picker?.LogName + " used " + item.Name; if (item.ContainedItems != null && item.ContainedItems.Any()) { logStr += " (" + string.Join(", ", item.ContainedItems.Select(i => i?.Name)) + ")"; } logStr += " on " + targetCharacter.LogName + "."; Networking.GameServer.Log(logStr, Networking.ServerLog.MessageType.Attack); } #endif if (targetCharacter != null) //TODO: Allow OnUse to happen on structures too maybe?? { ApplyStatusEffects(ActionType.OnUse, 1.0f, targetCharacter, targetLimb, user: User); } if (DeleteOnUse) { Entity.Spawner.AddToRemoveQueue(item); } return(true); }
protected Tuple <float, float> CalculateAffinity(int distanceToRoot, Dictionary <int, int[]> itemTokenPlaceMap, TokenZipNode tokenNode, int itemsCount, int encounterThreshold, HashSet <int> potentialPlaces, ref HashSet <int> itemTokensFound) { bool zipNodeMatches = (potentialPlaces?.Any() != false); if (zipNodeMatches && tokenNode.TokenId >= 0) { itemTokensFound.Add(tokenNode.TokenId); } float heightBonus = (float)Math.Log(distanceToRoot + 1); float tzWeight = tokenNode.TokenWeight * distanceToRoot * tokenNode.Encounters / itemsCount; if (tokenNode.IsLeaf) { if (zipNodeMatches) { // a complete matching chain gets emphasized by multiplying by its heigh tzWeight *= heightBonus; // added bonus for reaching the top return(new Tuple <float, float>(tzWeight, tzWeight)); } else { return(new Tuple <float, float>(0, tzWeight)); } } else { float matchingWeight = 0; float totalWeight = 0; foreach (TokenZipNode tzTreeChild in tokenNode.ChildNodes) { int[] tokenPlaceMap = null; bool startTokenFound = tzTreeChild.TokenId == TokenZipNode.WildcardId; if (!startTokenFound) { for (int i = 0; i < 3; i++) // TODO: HACK for some race condition causing nullref { try { startTokenFound = itemTokenPlaceMap.TryGetValue(tzTreeChild.TokenId, out tokenPlaceMap); break; } catch when(i < 2) { System.Threading.Tasks.Task.Delay(1).Wait(); // ugly hack for thread-contested itemTokenPlaceMap } } } // Say our token ID is 5 and the item has [2,3,4,5,4,3,5,7,9] tokens. // tokenPlaceMap[5] will be [3,6] // this means our next token must be 4 or 7 to match anything // if it's 4 then we remove the 3 from [3,6], if it's 7 - remove 6 // our potentialPlaces items must be present (at least some) in the tokenPlace map with an offset of DistanceToRoot // ie potentialPlaces[5,6] matches tokenPlaceMap[5+tz,DistanceToRoot] HashSet <int> nextPotentialPlaces = null; if (!startTokenFound) { if (nextPotentialPlaces == null) { nextPotentialPlaces = new HashSet <int>(); } } else { if (tokenPlaceMap != null) { // if there are potential places for next tokens - take them into account nextPotentialPlaces = potentialPlaces?.Any() == true ? new HashSet <int>(potentialPlaces.Except(tokenPlaceMap.Select(t => t + distanceToRoot))) : new HashSet <int>(tokenPlaceMap); } } Tuple <float, float> nodeAffinity = CalculateAffinity(distanceToRoot + 1, itemTokenPlaceMap, tzTreeChild, itemsCount, encounterThreshold, nextPotentialPlaces, ref itemTokensFound); if (tzTreeChild.Encounters + tzTreeChild.DistanceToRoot >= encounterThreshold) { if (nextPotentialPlaces?.Any() == true || tzTreeChild.TokenId == TokenZipNode.WildcardId) { matchingWeight += nodeAffinity.Item1; } totalWeight += nodeAffinity.Item2; } } if (matchingWeight > 0) { return(new Tuple <float, float>(matchingWeight + tzWeight, totalWeight + tzWeight)); } else if (tokenNode.Encounters + distanceToRoot >= encounterThreshold) { tzWeight *= heightBonus; return(new Tuple <float, float>(tzWeight, totalWeight + tzWeight)); } else { return(new Tuple <float, float>(0, 0)); } } }
/// <summary> /// Returns true if the given profile is supported. /// </summary> public bool Supports(string profileName) { return(_supportedProfiles.Any((x) => x.Equals(profileName, StringComparison.OrdinalIgnoreCase))); }
public override void ExecuteCmdlet() { base.ExecuteCmdlet(); SiteConfig siteConfig = null; string location = null; switch (ParameterSetName) { case ParameterSet1Name: WebApp = WebsitesClient.GetWebApp(ResourceGroupName, Name, null); location = WebApp.Location; var parameters = new HashSet <string>(MyInvocation.BoundParameters.Keys, StringComparer.OrdinalIgnoreCase); if (parameters.Any(p => CmdletHelpers.SiteConfigParameters.Contains(p))) { siteConfig = new SiteConfig { DefaultDocuments = parameters.Contains("DefaultDocuments") ? DefaultDocuments : null, NetFrameworkVersion = parameters.Contains("NetFrameworkVersion") ? NetFrameworkVersion : null, PhpVersion = parameters.Contains("PhpVersion") ? PhpVersion : null, RequestTracingEnabled = parameters.Contains("RequestTracingEnabled") ? (bool?)RequestTracingEnabled : null, HttpLoggingEnabled = parameters.Contains("HttpLoggingEnabled") ? (bool?)HttpLoggingEnabled : null, DetailedErrorLoggingEnabled = parameters.Contains("DetailedErrorLoggingEnabled") ? (bool?)DetailedErrorLoggingEnabled : null, HandlerMappings = parameters.Contains("HandlerMappings") ? HandlerMappings : null, ManagedPipelineMode = parameters.Contains("ManagedPipelineMode") ? (ManagedPipelineMode?)Enum.Parse(typeof(ManagedPipelineMode), ManagedPipelineMode) : null, WebSocketsEnabled = parameters.Contains("WebSocketsEnabled") ? (bool?)WebSocketsEnabled : null, Use32BitWorkerProcess = parameters.Contains("Use32BitWorkerProcess") ? (bool?)Use32BitWorkerProcess : null, AutoSwapSlotName = parameters.Contains("AutoSwapSlotName") ? AutoSwapSlotName : null, NumberOfWorkers = parameters.Contains("NumberOfWorkers") ? NumberOfWorkers : WebApp.SiteConfig.NumberOfWorkers }; } // Update web app configuration WebsitesClient.UpdateWebAppConfiguration(ResourceGroupName, location, Name, null, siteConfig, AppSettings.ConvertToStringDictionary(), ConnectionStrings.ConvertToConnectionStringDictionary()); if (parameters.Contains("AppServicePlan")) { WebsitesClient.UpdateWebApp(ResourceGroupName, location, Name, null, AppServicePlan); } if (parameters.Contains("HostNames")) { WebsitesClient.AddCustomHostNames(ResourceGroupName, location, Name, HostNames); } break; case ParameterSet2Name: // Web app is direct or pipeline input string servicePlanName; string rg; location = WebApp.Location; siteConfig = WebApp.SiteConfig; // Update web app configuration WebsitesClient.UpdateWebAppConfiguration( ResourceGroupName, location, Name, null, siteConfig, WebApp.SiteConfig == null ? null : WebApp.SiteConfig .AppSettings .ToDictionary( nvp => nvp.Name, nvp => nvp.Value, StringComparer.OrdinalIgnoreCase), WebApp.SiteConfig == null ? null : WebApp.SiteConfig .ConnectionStrings .ToDictionary( nvp => nvp.Name, nvp => new ConnStringValueTypePair { Type = nvp.Type.Value, Value = nvp.ConnectionString }, StringComparer.OrdinalIgnoreCase)); CmdletHelpers.TryParseAppServicePlanMetadataFromResourceId(WebApp.ServerFarmId, out rg, out servicePlanName); WebsitesClient.UpdateWebApp(ResourceGroupName, location, Name, null, servicePlanName); WebsitesClient.AddCustomHostNames(ResourceGroupName, location, Name, WebApp.HostNames.ToArray()); break; } WriteObject(WebsitesClient.GetWebApp(ResourceGroupName, Name, null)); }
public static bool IsPrimitive(Type type) { var typeWrapper = TypeFactory.GetTypeInfo(type); return(PrimitiveTypeInfos.Any(ti => typeWrapper.IsAssignableFrom(ti))); }
public virtual SerializedProperty DoInspectorGUI() { var slotContainer = targets[0] as VFXModel; List <VFXSetting> settingFields = slotContainer.GetSettings(false, VFXSettingAttribute.VisibleFlags.InInspector).ToList(); for (int i = 1; i < targets.Length; ++i) { IEnumerable <VFXSetting> otherSettingFields = (targets[i] as VFXModel).GetSettings(false, VFXSettingAttribute.VisibleFlags.InInspector).ToArray(); var excluded = new HashSet <NameNType>(settingFields.Select(t => new NameNType() { name = t.name, type = t.field.FieldType }).Except(otherSettingFields.Select(t => new NameNType() { name = t.name, type = t.field.FieldType }))); settingFields.RemoveAll(t => excluded.Any(u => u.name == t.name)); } SerializedProperty modifiedSetting = null; foreach (var prop in settingFields.Select(t => new KeyValuePair <VFXSetting, SerializedProperty>(t, FindProperty(t))).Where(t => t.Value != null)) { var fieldInfo = prop.Key.field; EditorGUI.BeginChangeCheck(); var attrs = fieldInfo.GetCustomAttributes(typeof(StringProviderAttribute), true); if (attrs.Length > 0) { var strings = StringPropertyRM.FindStringProvider(attrs)(); int selected = prop.Value.hasMultipleDifferentValues ? -1 : System.Array.IndexOf(strings, prop.Value.stringValue); int result = EditorGUILayout.Popup(ObjectNames.NicifyVariableName(prop.Value.name), selected, strings); if (result != selected) { prop.Value.stringValue = strings[result]; } } else if (fieldInfo.FieldType.IsEnum && fieldInfo.FieldType.GetCustomAttributes(typeof(FlagsAttribute), false).Length == 0) { GUIContent[] enumNames = null; int[] enumValues = null; Array enums = Enum.GetValues(fieldInfo.FieldType); List <int> values = new List <int>(enums.Length); for (int i = 0; i < enums.Length; ++i) { values.Add((int)enums.GetValue(i)); } foreach (var target in targets) { VFXModel targetIte = target as VFXModel; var filteredValues = targetIte.GetFilteredOutEnumerators(fieldInfo.Name); if (filteredValues != null) { foreach (int val in filteredValues) { values.Remove(val); } } } enumNames = values.Select(t => new GUIContent(Enum.GetName(fieldInfo.FieldType, t))).ToArray(); enumValues = values.ToArray(); HeaderAttribute attr = fieldInfo.GetCustomAttributes <HeaderAttribute>().FirstOrDefault(); if (attr != null) { GUILayout.Label(attr.header, EditorStyles.boldLabel); } EditorGUILayout.IntPopup(prop.Value, enumNames, enumValues); } else { bool visibleChildren = EditorGUILayout.PropertyField(prop.Value); if (visibleChildren) { SerializedProperty childProp = prop.Value.Copy(); while (childProp != null && childProp.NextVisible(visibleChildren) && childProp.propertyPath.StartsWith(prop.Value.propertyPath + ".")) { visibleChildren = EditorGUILayout.PropertyField(childProp); } } } if (EditorGUI.EndChangeCheck()) { modifiedSetting = prop.Value; } } return(modifiedSetting); }
private void BuildVehicleList(XPathNodeIterator objXmlVehicleList) { List <ListItem> lstVehicles = new List <ListItem>(); foreach (XPathNavigator objXmlVehicle in objXmlVehicleList) { if (chkHideOverAvailLimit.Checked && !SelectionShared.CheckAvailRestriction(objXmlVehicle, _objCharacter)) { continue; } if (!chkFreeItem.Checked && chkShowOnlyAffordItems.Checked) { decimal decCostMultiplier = 1.0m; if (chkUsedVehicle.Checked) { decCostMultiplier -= (nudUsedVehicleDiscount.Value / 100.0m); } decCostMultiplier *= 1 + (nudMarkup.Value / 100.0m); if (_setBlackMarketMaps.Contains(objXmlVehicle.SelectSingleNode("category")?.Value)) { decCostMultiplier *= 0.9m; } if (_setDealerConnectionMaps?.Any(set => objXmlVehicle.SelectSingleNode("category")?.Value.StartsWith(set) == true) == true) { decCostMultiplier *= 0.9m; } if (!SelectionShared.CheckNuyenRestriction(objXmlVehicle, _objCharacter.Nuyen, decCostMultiplier)) { continue; } } string strDisplayname = objXmlVehicle.SelectSingleNode("translate")?.Value ?? objXmlVehicle.SelectSingleNode("name")?.Value ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language); if (!_objCharacter.Options.SearchInCategoryOnly && txtSearch.TextLength != 0) { string strCategory = objXmlVehicle.SelectSingleNode("category")?.Value; if (!string.IsNullOrEmpty(strCategory)) { ListItem objFoundItem = _lstCategory.Find(objFind => objFind.Value.ToString() == strCategory); if (!string.IsNullOrEmpty(objFoundItem.Name)) { strDisplayname += " [" + objFoundItem.Name + ']'; } } } lstVehicles.Add(new ListItem(objXmlVehicle.SelectSingleNode("id")?.Value ?? string.Empty, strDisplayname)); } lstVehicles.Sort(CompareListItems.CompareNames); string strOldSelected = lstVehicle.SelectedValue?.ToString(); _blnLoading = true; lstVehicle.BeginUpdate(); lstVehicle.ValueMember = "Value"; lstVehicle.DisplayMember = "Name"; lstVehicle.DataSource = lstVehicles; _blnLoading = false; if (string.IsNullOrEmpty(strOldSelected)) { lstVehicle.SelectedIndex = -1; } else { lstVehicle.SelectedValue = strOldSelected; } lstVehicle.EndUpdate(); }
private void SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold(int threshold, UniquenessType uniqueBy) { dataGridView1.EndEdit(); var dubious = new HashSet <string>(); for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++) { var row = dataGridView1.Rows[rowIndex]; int matchCount = _peptidesInBackgroundProteome.Contains((PeptideDocNode)row.Tag) ? 1 : 0; for (int col = 0; col < dataGridView1.ColumnCount; col++) { if (col == PeptideIncludedColumn.Index || col == PeptideColumn.Index) { continue; } if (row.Cells[col].Value is bool && ((bool)row.Cells[col].Value)) { if (uniqueBy == UniquenessType.protein) { matchCount++; } else { var peptide = (PeptideDocNode)row.Tag; var parent = PeptideGroupDocNodes.First(p => p.Children.Contains(peptide)); string testValA; string testValB; // ATP5B and atp5b are the same thing, as are "mus musculus" and "MUS MUSCULUS" if (uniqueBy == UniquenessType.gene) { // ReSharper disable once PossibleNullReferenceException if (string.Compare(testValA = parent.ProteinMetadata.Gene, testValB = ((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Gene, StringComparison.OrdinalIgnoreCase) != 0) { matchCount++; } } else { // ReSharper disable once PossibleNullReferenceException if (string.Compare(testValA = parent.ProteinMetadata.Species, testValB = ((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Species, StringComparison.OrdinalIgnoreCase) != 0) { matchCount++; } } if (string.IsNullOrEmpty(testValA)) { dubious.Add(parent.Name); } if (string.IsNullOrEmpty(testValB)) { dubious.Add(((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Name); } } } if (matchCount > threshold) { break; } } row.Cells[PeptideIncludedColumn.Name].Value = (matchCount <= threshold); } SetCheckBoxPeptideIncludedHeaderState(); if (dubious.Any()) { var dubiousValues = TextUtil.LineSeparate(uniqueBy == UniquenessType.gene ? Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_background_proteome_proteins_did_not_have_gene_information__this_selection_may_be_suspect_ : Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_background_proteome_proteins_did_not_have_species_information__this_selection_may_be_suspect_, Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_These_proteins_include_, TextUtil.LineSeparate(dubious)); // Not L10N MessageDlg.Show(this, dubiousValues); } }
private void Match(DirectoryInfoBase directory, string parentRelativePath) { // Request all the including and excluding patterns to push current directory onto their status stack. PushDirectory(directory); Declare(); var entities = new List <FileSystemInfoBase>(); if (_declaredWildcardPathSegment || _declaredLiteralFileSegments.Any()) { entities.AddRange(directory.EnumerateFileSystemInfos()); } else { var candidates = directory.EnumerateFileSystemInfos().OfType <DirectoryInfoBase>(); foreach (var candidate in candidates) { if (_declaredLiteralFolderSegmentInString.Contains(candidate.Name)) { entities.Add(candidate); } } } if (_declaredParentPathSegment) { entities.Add(directory.GetDirectory("..")); } // collect files and sub directories var subDirectories = new List <DirectoryInfoBase>(); foreach (var entity in entities) { var fileInfo = entity as FileInfoBase; if (fileInfo != null) { var result = MatchPatternContexts(fileInfo, (pattern, file) => pattern.Test(file)); if (result.IsSuccessful) { _files.Add(new FilePatternMatch( path: CombinePath(parentRelativePath, fileInfo.Name), stem: result.Stem)); } continue; } var directoryInfo = entity as DirectoryInfoBase; if (directoryInfo != null) { if (MatchPatternContexts(directoryInfo, (pattern, dir) => pattern.Test(dir))) { subDirectories.Add(directoryInfo); } continue; } } // Matches the sub directories recursively foreach (var subDir in subDirectories) { var relativePath = CombinePath(parentRelativePath, subDir.Name); Match(subDir, relativePath); } // Request all the including and excluding patterns to pop their status stack. PopDirectory(); }
private async Task StartServerCache(EmbyServers server, EmbySettings settings) { if (!ValidateSettings(server)) { return; } //await _repo.ExecuteSql("DELETE FROM EmbyEpisode"); //await _repo.ExecuteSql("DELETE FROM EmbyContent"); var movies = await Api.GetAllMovies(server.ApiKey, 0, 200, server.AdministratorId, server.FullUri); var totalCount = movies.TotalRecordCount; var processed = 1; var mediaToAdd = new HashSet <EmbyContent>(); while (processed < totalCount) { foreach (var movie in movies.Items) { if (movie.Type.Equals("boxset", StringComparison.InvariantCultureIgnoreCase)) { var movieInfo = await Api.GetCollection(movie.Id, server.ApiKey, server.AdministratorId, server.FullUri); foreach (var item in movieInfo.Items) { await ProcessMovies(item, mediaToAdd, server); } processed++; } else { processed++; // Regular movie await ProcessMovies(movie, mediaToAdd, server); } } // Get the next batch movies = await Api.GetAllMovies(server.ApiKey, processed, 200, server.AdministratorId, server.FullUri); await _repo.AddRange(mediaToAdd); mediaToAdd.Clear(); } // TV Time var tv = await Api.GetAllShows(server.ApiKey, 0, 200, server.AdministratorId, server.FullUri); var totalTv = tv.TotalRecordCount; processed = 1; while (processed < totalTv) { foreach (var tvShow in tv.Items) { try { processed++; if (string.IsNullOrEmpty(tvShow.ProviderIds?.Tvdb)) { _logger.LogInformation("Provider Id on tv {0} is null", tvShow.Name); continue; } var existingTv = await _repo.GetByEmbyId(tvShow.Id); if (existingTv == null) { _logger.LogDebug("Adding new TV Show {0}", tvShow.Name); mediaToAdd.Add(new EmbyContent { TvDbId = tvShow.ProviderIds?.Tvdb, ImdbId = tvShow.ProviderIds?.Imdb, TheMovieDbId = tvShow.ProviderIds?.Tmdb, Title = tvShow.Name, Type = EmbyMediaType.Series, EmbyId = tvShow.Id, Url = EmbyHelper.GetEmbyMediaUrl(tvShow.Id, server?.ServerId, server.ServerHostname), AddedAt = DateTime.UtcNow }); } else { _logger.LogDebug("We already have TV Show {0}", tvShow.Name); } } catch (Exception) { throw; } } // Get the next batch tv = await Api.GetAllShows(server.ApiKey, processed, 200, server.AdministratorId, server.FullUri); await _repo.AddRange(mediaToAdd); mediaToAdd.Clear(); } if (mediaToAdd.Any()) { await _repo.AddRange(mediaToAdd); } }
/// <summary> /// Returns server capabilities string /// </summary> /// <param name="caps">Capabilities.</param> /// <returns></returns> internal static string GetServerCapabilitiesAsString(HashSet <string> caps) { return(caps?.Any() ?? false? caps.Aggregate((x, y) => $"{x},{y}") : string.Empty); }
List <ILNode> ConvertToAst(List <ByteCode> body, HashSet <ExceptionHandler> ehs) { List <ILNode> ast = new List <ILNode>(); while (ehs.Any()) { ILTryCatchBlock tryCatchBlock = new ILTryCatchBlock(); // Find the first and widest scope int tryStart = ehs.Min(eh => eh.TryStart.Offset); int tryEnd = ehs.Where(eh => eh.TryStart.Offset == tryStart).Max(eh => eh.TryEnd.Offset); var handlers = ehs.Where(eh => eh.TryStart.Offset == tryStart && eh.TryEnd.Offset == tryEnd).ToList(); // Cut all instructions up to the try block { int tryStartIdx; for (tryStartIdx = 0; body[tryStartIdx].Offset != tryStart; tryStartIdx++) { ; } ast.AddRange(ConvertToAst(body.CutRange(0, tryStartIdx))); } // Cut the try block { HashSet <ExceptionHandler> nestedEHs = new HashSet <ExceptionHandler>(ehs.Where(eh => (tryStart <= eh.TryStart.Offset && eh.TryEnd.Offset < tryEnd) || (tryStart < eh.TryStart.Offset && eh.TryEnd.Offset <= tryEnd))); ehs.ExceptWith(nestedEHs); int tryEndIdx; for (tryEndIdx = 0; tryEndIdx < body.Count && body[tryEndIdx].Offset != tryEnd; tryEndIdx++) { ; } tryCatchBlock.TryBlock = new ILBlock(ConvertToAst(body.CutRange(0, tryEndIdx), nestedEHs)); } // Cut all handlers tryCatchBlock.CatchBlocks = new List <ILTryCatchBlock.CatchBlock>(); foreach (ExceptionHandler eh in handlers) { int startIndex; for (startIndex = 0; body[startIndex].Offset != eh.HandlerStart.Offset; startIndex++) { ; } int endInclusiveIndex; if (eh.HandlerEnd == null) { endInclusiveIndex = body.Count - 1; } // Note that the end(exclusive) instruction may not necessarly be in our body else { for (endInclusiveIndex = 0; body[endInclusiveIndex].Next.Offset != eh.HandlerEnd.Offset; endInclusiveIndex++) { ; } } int count = 1 + endInclusiveIndex - startIndex; HashSet <ExceptionHandler> nestedEHs = new HashSet <ExceptionHandler>(ehs.Where(e => (eh.HandlerStart.Offset <= e.TryStart.Offset && e.TryEnd.Offset < eh.HandlerEnd.Offset) || (eh.HandlerStart.Offset < e.TryStart.Offset && e.TryEnd.Offset <= eh.HandlerEnd.Offset))); ehs.ExceptWith(nestedEHs); List <ILNode> handlerAst = ConvertToAst(body.CutRange(startIndex, count), nestedEHs); if (eh.HandlerType == ExceptionHandlerType.Catch) { ILTryCatchBlock.CatchBlock catchBlock = new ILTryCatchBlock.CatchBlock() { ExceptionType = eh.CatchType, Body = handlerAst }; // Handle the automatically pushed exception on the stack ByteCode ldexception = ldexceptions[eh]; if (ldexception.StoreTo.Count == 0) { throw new Exception("Exception should be consumed by something"); } else if (ldexception.StoreTo.Count == 1) { ILExpression first = catchBlock.Body[0] as ILExpression; if (first != null && first.Code == ILCode.Pop && first.Arguments[0].Code == ILCode.Ldloc && first.Arguments[0].Operand == ldexception.StoreTo[0]) { // The exception is just poped - optimize it all away; catchBlock.ExceptionVariable = null; catchBlock.Body.RemoveAt(0); } else { catchBlock.ExceptionVariable = ldexception.StoreTo[0]; } } else { ILVariable exTemp = new ILVariable() { Name = "ex_" + eh.HandlerStart.Offset.ToString("X2"), IsGenerated = true }; catchBlock.ExceptionVariable = exTemp; foreach (ILVariable storeTo in ldexception.StoreTo) { catchBlock.Body.Insert(0, new ILExpression(ILCode.Stloc, storeTo, new ILExpression(ILCode.Ldloc, exTemp))); } } tryCatchBlock.CatchBlocks.Add(catchBlock); } else if (eh.HandlerType == ExceptionHandlerType.Finally) { tryCatchBlock.FinallyBlock = new ILBlock(handlerAst); } else if (eh.HandlerType == ExceptionHandlerType.Fault) { tryCatchBlock.FaultBlock = new ILBlock(handlerAst); } else { // TODO: ExceptionHandlerType.Filter } } ehs.ExceptWith(handlers); ast.Add(tryCatchBlock); } // Add whatever is left ast.AddRange(ConvertToAst(body)); return(ast); }
static void ApplyRules(ModData modData, IEnumerable <UpdateRule> rules, bool skipMaps) { Console.WriteLine(); var logWriter = File.CreateText("update.log"); logWriter.AutoFlush = true; var externalFilenames = new HashSet <string>(); foreach (var rule in rules) { var manualSteps = new List <string>(); var allFiles = new YamlFileSet(); LogLine(logWriter, "{0}: {1}", rule.GetType().Name, rule.Name); try { Log(logWriter, " Updating mod... "); manualSteps.AddRange(UpdateUtils.UpdateMod(modData, rule, out allFiles, externalFilenames)); LogLine(logWriter, "COMPLETE"); } catch (Exception ex) { Console.WriteLine("FAILED"); LogLine(logWriter); LogLine(logWriter, " The automated changes for this rule were not applied because of an error."); LogLine(logWriter, " After the issue reported below is resolved you should run the updater"); LogLine(logWriter, " with SOURCE set to {0} to retry these changes", rule.GetType().Name); LogLine(logWriter); LogLine(logWriter, " The exception reported was:"); LogLine(logWriter, " " + ex.ToString().Replace("\n", "\n ")); continue; } Log(logWriter, " Updating system maps... "); if (!skipMaps) { var mapsFailed = false; var mapExternalFilenames = new HashSet <string>(); foreach (var package in modData.MapCache.EnumerateMapPackagesWithoutCaching()) { try { YamlFileSet mapFiles; var mapSteps = UpdateUtils.UpdateMap(modData, package, rule, out mapFiles, mapExternalFilenames); allFiles.AddRange(mapFiles); if (mapSteps.Any()) { manualSteps.Add("Map: " + package.Name + ":\n" + UpdateUtils.FormatMessageList(mapSteps)); } } catch (Exception ex) { LogLine(logWriter, "FAILED"); LogLine(logWriter); LogLine(logWriter, " The automated changes for this rule were not applied because of an error."); LogLine(logWriter, " After the issue reported below is resolved you should run the updater"); LogLine(logWriter, " with SOURCE set to {0} to retry these changes", rule.GetType().Name); LogLine(logWriter); LogLine(logWriter, " The map that caused the error was:"); LogLine(logWriter, " " + package.Name); LogLine(logWriter); LogLine(logWriter, " The exception reported was:"); LogLine(logWriter, " " + ex.ToString().Replace("\n", "\n ")); mapsFailed = true; break; } } if (mapsFailed) { continue; } LogLine(logWriter, "COMPLETE"); } else { LogLine(logWriter, "SKIPPED"); } // Files are saved after each successful automated rule update allFiles.Save(); if (manualSteps.Any()) { LogLine(logWriter, " Manual changes are required to complete this update:"); LogLine(logWriter, UpdateUtils.FormatMessageList(manualSteps, 1)); } LogLine(logWriter); } if (externalFilenames.Any()) { LogLine(logWriter, "The following external mod files have been ignored:"); LogLine(logWriter, UpdateUtils.FormatMessageList(externalFilenames)); LogLine(logWriter, "These files should be updated by running --update-mod on the referenced mod(s)"); LogLine(logWriter); } Console.WriteLine("Semi-automated update complete."); Console.WriteLine("Please review the messages above for any manual actions that must be applied."); Console.WriteLine("These messages have also been written to an update.log file in the current directory."); }
/// <summary> /// Trims the Results of evaluating the inner pattern to remove Variables which are not Result Variables. /// </summary> /// <param name="context">Evaluation Context.</param> /// <returns></returns> public BaseMultiset Evaluate(SparqlEvaluationContext context) { try { context.InputMultiset = context.Evaluate(_pattern); } catch (RdfQueryTimeoutException) { // If not partial results throw the error if (context.Query == null || !context.Query.PartialResultsOnTimeout) { throw; } } // Ensure expected variables are present HashSet <SparqlVariable> vars = new HashSet <SparqlVariable>(_variables); if (context.InputMultiset is NullMultiset) { context.InputMultiset = new Multiset(vars.Select(v => v.Name)); } else if (context.InputMultiset is IdentityMultiset) { context.InputMultiset = new Multiset(vars.Select(v => v.Name)); context.InputMultiset.Add(new Set()); } else if (context.InputMultiset.IsEmpty) { foreach (SparqlVariable var in vars) { context.InputMultiset.AddVariable(var.Name); } } // Trim Variables that aren't being SELECTed if (!IsSelectAll) { foreach (String var in context.InputMultiset.Variables.ToList()) { if (!vars.Any(v => v.Name.Equals(var) && v.IsResultVariable)) { // If not a Result variable then trim from results context.InputMultiset.Trim(var); } } } // Ensure all SELECTed variables are present foreach (SparqlVariable var in vars) { if (!context.InputMultiset.ContainsVariable(var.Name)) { context.InputMultiset.AddVariable(var.Name); } } context.OutputMultiset = context.InputMultiset; // Apply variable ordering if applicable if (!IsSelectAll && (context.Query == null || SparqlSpecsHelper.IsSelectQuery(context.Query.QueryType))) { context.OutputMultiset.SetVariableOrder(context.Query.Variables.Where(v => v.IsResultVariable).Select(v => v.Name)); } return(context.OutputMultiset); }
public static Dictionary <string, TimeEntryBlock> ConvertTimeEntriesToBlocks(List <Toggl.TogglTimeEntryView> timeEntries, Toggl.TogglTimeEntryView?runningEntry, int selectedScaleMode, DateTime selectedDate, DateTime now) { var timeStampsList = new List <(TimeStampType Type, TimeEntryBlock Block)>(); var blocks = new Dictionary <string, TimeEntryBlock>(); //The idea is to place all the starts and ends in sorted order and then assign an offset to each time entry block from the list: // - if it's a start time stamp, then pick up the minimum available offset, if none is available assign a new one. // - if it's an end time stamp, then release the offset which it occupied. IEnumerable <Toggl.TogglTimeEntryView> allEntries = timeEntries; if (runningEntry != null && runningEntry.Value.StartTime().Date <= selectedDate.Date && now.Date >= selectedDate.Date) { allEntries = allEntries.Union(new List <Toggl.TogglTimeEntryView>() { runningEntry.Value }); } foreach (var entry in allEntries) { if (blocks.ContainsKey(entry.GUID)) { continue; } var startTime = entry.StartTime(); var ended = entry.GUID == runningEntry?.GUID ? (ulong)Toggl.UnixFromDateTime(now) : entry.Ended; var height = ConvertTimeIntervalToHeight(startTime, Toggl.DateTimeFromUnix(ended), selectedScaleMode); var block = new TimeEntryBlock(entry, TimelineConstants.ScaleModes[selectedScaleMode], selectedDate) { Height = height, VerticalOffset = ConvertTimeIntervalToHeight(selectedDate, startTime, selectedScaleMode), IsOverlapping = false }; if (entry.Started < ended) { timeStampsList.Add((TimeStampType.Start, block)); timeStampsList.Add((TimeStampType.End, block)); } else { timeStampsList.Add((TimeStampType.Empty, block)); } blocks.Add(entry.GUID, block); } //There can be a situation that next time entry starts exactly at the same moment, the previous one ended. //This situation must not be considered as overlap. So the comparison logic if time stamps are the same: // - always place the end time stamps first // - prefer empty time stamps to start time stamps // (otherwise if we discover a start then an empty, this will be considered as overlap, which we want to avoid) timeStampsList.Sort((te1, te2) => { var time1 = te1.Type == TimeStampType.End ? te1.Block.Bottom : te1.Block.VerticalOffset; var time2 = te2.Type == TimeStampType.End ? te2.Block.Bottom : te2.Block.VerticalOffset; var res = time1 - time2; if (res.IsNearEqual(0, TimelineConstants.AcceptableBlocksOverlap)) { var getPriority = new Func <TimeStampType, int>(t => t == TimeStampType.End ? 0 : t == TimeStampType.Empty ? 1 : 2); return(getPriority(te1.Type) - getPriority(te2.Type)); } return(res < 0 ? -1 : 1); }); var offsets = new HashSet <double>(); var curOffset = 0d; var usedNumOfOffsets = 0; TimeEntryBlock prevLayerBlock = null; foreach (var item in timeStampsList) { if (item.Type == TimeStampType.Start || item.Type == TimeStampType.Empty) { if (!offsets.Any()) { offsets.Add(curOffset); curOffset += TimelineConstants.TimeEntryBlockWidth + TimelineConstants.GapBetweenOverlappingTEs; } if (usedNumOfOffsets > 0) { item.Block.IsOverlapping = true; if (prevLayerBlock != null) { prevLayerBlock.IsOverlapping = true; } } item.Block.HorizontalOffset = offsets.Min(); offsets.Remove(offsets.Min()); usedNumOfOffsets++; prevLayerBlock = item.Block; } if (item.Type == TimeStampType.End || item.Type == TimeStampType.Empty) { offsets.Add(item.Block.HorizontalOffset); usedNumOfOffsets--; prevLayerBlock = null; } } return(blocks); }
void ITick.Tick(Actor self) { if (!Army.Any() && !Commanders.Any() && !Utilities.Any() && CountdownTimer <= 0) { EndWarOnEmpty(self); return; } if (armyassamble) { if (SearchTickTimer > 0) { SearchTickTimer--; } if (SearchTickTimer <= 0) { BuildTheArmy(self); SearchTickTimer = info.SearchTick; } } if ((Army.Any() || Commanders.Any() || Utilities.Any()) && !armyonwords && !gatherup && CountdownTimer > 0) { CountdownTimer--; message = "Attack in " + CountdownTimer / 25 + " seconds"; return; } if ((Army.Any() || Commanders.Any() || Utilities.Any()) && !armyonwords && !gatherup && CountdownTimer <= 0) { AttackPlayer = FetchforPlayer(self); if (AttackPlayer == null) { AttackPlayer = Randomplayer(self); } else if (AttackPlayer.WinState == WinState.Lost) { AttackPlayer = Randomplayer(self); } message = "Attacking Player " + AttackPlayer.PlayerName; if (AttackPlayer != null) { armyassamble = false; gatherup = true; if (reducer > 1000) { reducer += info.Counttdownreducer; } if (GatherLocation == CPos.Zero) { var loc = Location(self, AttackPlayer, self.Location).Location; GatherLocation = MeetupPoint(self, Army, loc); if (GatherLocation == CPos.Zero) { return; } } if (Army.Any()) { ForceArmyGather(Army, GatherLocation); } if (Commanders.Any()) { ForceArmyGather(Commanders, GatherLocation); } if (Utilities.Any()) { ForceArmyGather(Utilities, GatherLocation); } } } if (gatherup) { if (SearchTickTimer > 0) { SearchTickTimer--; } if (SearchTickTimer <= 0) { message = "Gather up at " + GatherLocation.ToString(); SearchTickTimer = 100; Army = CheckForLiving(Army); Commanders = CheckForLiving(Commanders); Utilities = CheckForLiving(Utilities); if (!Army.Any() && !Commanders.Any() && !Utilities.Any()) { EndWarOnEmpty(self); return; } if (AttackPlayer == null) { AttackPlayer = Randomplayer(self); } else if (AttackPlayer.WinState == WinState.Lost) { AttackPlayer = Randomplayer(self); } if (GatherLocation == CPos.Zero) { var loc = Location(self, AttackPlayer, self.Location).Location; GatherLocation = MeetupPoint(self, Army, loc); if (GatherLocation == CPos.Zero) { return; } } bool true1 = IdleArmyGather(Army, self, GatherLocation, 5); bool true2 = IdleArmyGather(Commanders, self, GatherLocation, 5); bool true3 = IdleArmyGather(Utilities, self, GatherLocation, 5); //Log.Write("debug","Check Army ready: " + true1); if (true1 && true2 && true3) { if (AttackPlayer != null && AttackPlayer.WinState != WinState.Lost) { AttackLocation = Location(self, AttackPlayer, GatherLocation); } else if (AttackPlayer == null) { AttackPlayer = Randomplayer(self); } else if (AttackPlayer.WinState == WinState.Lost) { AttackPlayer = Randomplayer(self); } GatherLocation = CPos.Zero; armyonwords = true; gatherup = false; } } } if (armyonwords) { if (SearchTickTimer > 0) { SearchTickTimer--; } if (SearchTickTimer <= 0) { if (AttackLocation != null && AttackLocation.Info.HasTraitInfo <TooltipInfo>()) { message = "Attack " + AttackLocation.Info.TraitInfo <TooltipInfo>().Name; } SearchTickTimer = 50; Army = CheckForLiving(Army); Commanders = CheckForLiving(Commanders); Utilities = CheckForLiving(Utilities); if (!Army.Any() && !Commanders.Any() && !Utilities.Any()) { EndWarOnEmpty(self); return; } if (AttackPlayer.WinState == WinState.Lost) { armyonwords = false; gatherup = false; armyassamble = true; CountdownTimer = info.Countdown; CountdownTimer -= reducer; SearchTickTimer = info.SearchTick; GatherLocation = CPos.Zero; } if (AttackLocation == null) { AttackLocation = Location(self, AttackPlayer, GatherLocation); } else if (AttackLocation.IsDead || !AttackLocation.IsInWorld) { AttackLocation = Location(self, AttackPlayer, GatherLocation); } if (Army.Any()) { IdleArmyAttack(Army); } if (Commanders.Any()) { IdleArmyAttack(Commanders); } if (Utilities.Any()) { IdleArmyAttack(Utilities); } } } }
public void ProcessSerializers(CecilSerializerContext context) { var references = new HashSet <AssemblyDefinition>(); EnumerateReferences(references, context.Assembly); var coreAssembly = CecilExtensions.FindCorlibAssembly(context.Assembly); // Only process assemblies depending on Stride.Engine if (!references.Any(x => x.Name.Name == "Stride.Engine")) { // Make sure Stride.Engine.Serializers can access everything internally var internalsVisibleToAttribute = coreAssembly.MainModule.GetTypeResolved(typeof(InternalsVisibleToAttribute).FullName); var serializationAssemblyName = "Stride.Engine.Serializers"; // Add [InteralsVisibleTo] attribute var internalsVisibleToAttributeCtor = context.Assembly.MainModule.ImportReference(internalsVisibleToAttribute.GetConstructors().Single()); var internalsVisibleAttribute = new CustomAttribute(internalsVisibleToAttributeCtor) { ConstructorArguments = { new CustomAttributeArgument(context.Assembly.MainModule.ImportReference(context.Assembly.MainModule.TypeSystem.String), serializationAssemblyName) } }; context.Assembly.CustomAttributes.Add(internalsVisibleAttribute); return; } var strideEngineAssembly = context.Assembly.Name.Name == "Stride.Engine" ? context.Assembly : context.Assembly.MainModule.AssemblyResolver.Resolve(new AssemblyNameReference("Stride.Engine", null)); var strideEngineModule = strideEngineAssembly.MainModule; // Generate IL for Stride.Core if (context.Assembly.Name.Name == "Stride.Engine") { ProcessStrideEngineAssembly(context); } var updatableFieldGenericType = strideEngineModule.GetType("Stride.Updater.UpdatableField`1"); updatableFieldGenericCtor = updatableFieldGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic); updatablePropertyGenericType = strideEngineModule.GetType("Stride.Updater.UpdatableProperty`1"); updatablePropertyGenericCtor = updatablePropertyGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic); var updatablePropertyObjectGenericType = strideEngineModule.GetType("Stride.Updater.UpdatablePropertyObject`1"); updatablePropertyObjectGenericCtor = updatablePropertyObjectGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic); var updatableListUpdateResolverGenericType = strideEngineModule.GetType("Stride.Updater.ListUpdateResolver`1"); updatableListUpdateResolverGenericCtor = updatableListUpdateResolverGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic); var updatableArrayUpdateResolverGenericType = strideEngineModule.GetType("Stride.Updater.ArrayUpdateResolver`1"); updatableArrayUpdateResolverGenericCtor = updatableArrayUpdateResolverGenericType.Methods.First(x => x.IsConstructor && !x.IsStatic); var parameterCollectionResolver = strideEngineModule.GetType("Stride.Engine.Design.ParameterCollectionResolver"); parameterCollectionResolverInstantiateValueAccessor = parameterCollectionResolver.Methods.First(x => x.Name == "InstantiateValueAccessor"); var registerMemberMethod = strideEngineModule.GetType("Stride.Updater.UpdateEngine").Methods.First(x => x.Name == "RegisterMember"); updateEngineRegisterMemberMethod = context.Assembly.MainModule.ImportReference(registerMemberMethod); var registerMemberResolverMethod = strideEngineModule.GetType("Stride.Updater.UpdateEngine").Methods.First(x => x.Name == "RegisterMemberResolver"); //pclVisitor.VisitMethod(registerMemberResolverMethod); updateEngineRegisterMemberResolverMethod = context.Assembly.MainModule.ImportReference(registerMemberResolverMethod); var typeType = coreAssembly.MainModule.GetTypeResolved(typeof(Type).FullName); getTypeFromHandleMethod = context.Assembly.MainModule.ImportReference(typeType.Methods.First(x => x.Name == "GetTypeFromHandle")); var mainPrepareMethod = CreateUpdateMethod(context.Assembly); // Emit serialization code for all the types we care about var processedTypes = new HashSet <TypeDefinition>(TypeReferenceEqualityComparer.Default); foreach (var serializableType in context.SerializableTypesProfiles.SelectMany(x => x.Value.SerializableTypes)) { // Special case: when processing Stride.Engine assembly, we automatically add dependent assemblies types too if (!serializableType.Value.Local && strideEngineAssembly != context.Assembly) { continue; } var typeDefinition = serializableType.Key as TypeDefinition; if (typeDefinition == null) { continue; } // Ignore already processed types if (!processedTypes.Add(typeDefinition)) { continue; } try { ProcessType(context, context.Assembly.MainModule.ImportReference(typeDefinition), mainPrepareMethod); } catch (Exception e) { throw new InvalidOperationException(string.Format("Error when generating update engine code for {0}", typeDefinition), e); } } // Force generic instantiations var il = mainPrepareMethod.Body.GetILProcessor(); foreach (var serializableType in context.SerializableTypesProfiles.SelectMany(x => x.Value.SerializableTypes).ToArray()) { // Special case: when processing Stride.Engine assembly, we automatically add dependent assemblies types too if (!serializableType.Value.Local && strideEngineAssembly != context.Assembly) { continue; } // Try to find if original method definition was generated var typeDefinition = serializableType.Key.Resolve(); // If using List<T>, register this type in UpdateEngine var parentTypeDefinition = typeDefinition; while (parentTypeDefinition != null) { var listInterfaceType = parentTypeDefinition.Interfaces.Select(x => x.InterfaceType).OfType <GenericInstanceType>().FirstOrDefault(x => x.ElementType.FullName == typeof(IList <>).FullName); if (listInterfaceType != null) { //call Updater.UpdateEngine.RegisterMemberResolver(new Updater.ListUpdateResolver<T>()); var elementType = ResolveGenericsVisitor.Process(serializableType.Key, listInterfaceType.GenericArguments[0]); il.Emit(OpCodes.Newobj, context.Assembly.MainModule.ImportReference(updatableListUpdateResolverGenericCtor).MakeGeneric(context.Assembly.MainModule.ImportReference(elementType))); il.Emit(OpCodes.Call, updateEngineRegisterMemberResolverMethod); } parentTypeDefinition = parentTypeDefinition.BaseType?.Resolve(); } // Same for arrays var arrayType = serializableType.Key as ArrayType; if (arrayType != null) { //call Updater.UpdateEngine.RegisterMemberResolver(new Updater.ArrayUpdateResolver<T>()); var elementType = ResolveGenericsVisitor.Process(serializableType.Key, arrayType.ElementType); il.Emit(OpCodes.Newobj, context.Assembly.MainModule.ImportReference(updatableArrayUpdateResolverGenericCtor).MakeGeneric(context.Assembly.MainModule.ImportReference(elementType))); il.Emit(OpCodes.Call, updateEngineRegisterMemberResolverMethod); } // Generic instantiation for AOT platforms if (context.Platform == Core.PlatformType.iOS && serializableType.Key.Name == "ValueParameterKey`1") { var keyType = ((GenericInstanceType)serializableType.Key).GenericArguments[0]; il.Emit(OpCodes.Call, context.Assembly.MainModule.ImportReference(parameterCollectionResolverInstantiateValueAccessor).MakeGenericMethod(context.Assembly.MainModule.ImportReference(keyType))); } var genericInstanceType = serializableType.Key as GenericInstanceType; if (genericInstanceType != null) { var expectedUpdateMethodName = ComputeUpdateMethodName(typeDefinition); var updateMethod = GetOrCreateUpdateType(typeDefinition.Module.Assembly, false)?.Methods.FirstOrDefault(x => x.Name == expectedUpdateMethodName && x.HasGenericParameters && x.GenericParameters.Count == genericInstanceType.GenericParameters.Count); // If nothing was found in main assembly, also look in Stride.Engine assembly, just in case (it might defines some shared/corlib types -- currently not the case) if (updateMethod == null) { updateMethod = GetOrCreateUpdateType(strideEngineAssembly, false)?.Methods.FirstOrDefault(x => x.Name == expectedUpdateMethodName && x.HasGenericParameters && x.GenericParameters.Count == genericInstanceType.GenericParameters.Count); } if (updateMethod != null) { // Emit call to update engine setup method with generic arguments of current type il.Emit(OpCodes.Call, context.Assembly.MainModule.ImportReference(updateMethod) .MakeGenericMethod(genericInstanceType.GenericArguments .Select(context.Assembly.MainModule.ImportReference) .ToArray())); } } } il.Emit(OpCodes.Ret); }
public static BuildResult Compile(ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) { var compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters(); var projectParameters = (CSharpProjectParameters)configuration.ProjectParameters ?? new CSharpProjectParameters(); FilePath outputName = configuration.CompiledOutputName; string responseFileName = Path.GetTempFileName(); //make sure that the output file is writable if (File.Exists(outputName)) { bool isWriteable = false; int count = 0; do { try { outputName.MakeWritable(); using (var stream = File.OpenWrite(outputName)) { isWriteable = true; } } catch (Exception) { Thread.Sleep(20); } } while (count++ < 5 && !isWriteable); if (!isWriteable) { MessageService.ShowError(string.Format(GettextCatalog.GetString("Can't lock file: {0}."), outputName)); return(null); } } //get the runtime TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime; DotNetProject project = configuration.ParentItem as DotNetProject; if (project != null) { runtime = project.TargetRuntime; } //get the compiler name string compilerName; try { compilerName = GetCompilerName(runtime, configuration.TargetFramework); } catch (Exception e) { string message = "Could not obtain a C# compiler"; monitor.ReportError(message, e); return(null); } var sb = new StringBuilder(); HashSet <string> alreadyAddedReference = new HashSet <string> (); var monoRuntime = runtime as MonoTargetRuntime; if (!compilerParameters.NoStdLib && (monoRuntime == null || monoRuntime.HasMultitargetingMcs)) { string corlib = project.AssemblyContext.GetAssemblyFullName("mscorlib", project.TargetFramework); if (corlib != null) { corlib = project.AssemblyContext.GetAssemblyLocation(corlib, project.TargetFramework); } if (corlib == null) { var br = new BuildResult(); br.AddError(string.Format("Could not find mscorlib for framework {0}", project.TargetFramework.Id)); return(br); } AppendQuoted(sb, "/r:", corlib); sb.AppendLine("-nostdlib"); } List <string> gacRoots = new List <string> (); sb.AppendFormat("\"/out:{0}\"", outputName); sb.AppendLine(); foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ()) { if (lib.ReferenceType == ReferenceType.Project) { var ownerProject = lib.OwnerProject; if (ownerProject != null) { var parentSolution = ownerProject.ParentSolution; if (parentSolution != null && !(parentSolution.FindProjectByName(lib.Reference) is DotNetProject)) { continue; } } } string refPrefix = string.IsNullOrEmpty(lib.Aliases) ? "" : lib.Aliases + "="; foreach (string fileName in lib.GetReferencedFileNames(configSelector)) { switch (lib.ReferenceType) { case ReferenceType.Package: SystemPackage pkg = lib.Package; if (pkg == null) { string msg = string.Format(GettextCatalog.GetString("{0} could not be found or is invalid."), lib.Reference); monitor.ReportWarning(msg); continue; } if (alreadyAddedReference.Add(fileName)) { AppendQuoted(sb, "/r:", refPrefix + fileName); } if (pkg.GacRoot != null && !gacRoots.Contains(pkg.GacRoot)) { gacRoots.Add(pkg.GacRoot); } if (!string.IsNullOrEmpty(pkg.Requires)) { foreach (string requiredPackage in pkg.Requires.Split(' ')) { SystemPackage rpkg = runtime.AssemblyContext.GetPackage(requiredPackage); if (rpkg == null) { continue; } foreach (SystemAssembly assembly in rpkg.Assemblies) { if (alreadyAddedReference.Add(assembly.Location)) { AppendQuoted(sb, "/r:", assembly.Location); } } } } break; default: if (alreadyAddedReference.Add(fileName)) { AppendQuoted(sb, "/r:", refPrefix + fileName); } break; } } } if (alreadyAddedReference.Any(reference => SystemAssemblyService.ContainsReferenceToSystemRuntime(reference))) { LoggingService.LogInfo("Found PCLv2 assembly."); var facades = runtime.FindFacadeAssembliesForPCL(project.TargetFramework); foreach (var facade in facades) { AppendQuoted(sb, "/r:", facade); } } string sysCore = project.AssemblyContext.GetAssemblyFullName("System.Core", project.TargetFramework); if (sysCore != null && !alreadyAddedReference.Contains(sysCore)) { var asm = project.AssemblyContext.GetAssemblyFromFullName(sysCore, null, project.TargetFramework); if (asm != null) { AppendQuoted(sb, "/r:", asm.Location); } } sb.AppendLine("/nologo"); sb.Append("/warn:"); sb.Append(compilerParameters.WarningLevel.ToString()); sb.AppendLine(); if (configuration.SignAssembly) { if (File.Exists(configuration.AssemblyKeyFile)) { AppendQuoted(sb, "/keyfile:", configuration.AssemblyKeyFile); } if (configuration.DelaySign) { sb.AppendLine("/delaySign"); } } var debugType = compilerParameters.DebugType; if (string.IsNullOrEmpty(debugType)) { debugType = configuration.DebugMode ? "full" : "none"; } else if (string.Equals(debugType, "pdbonly", StringComparison.OrdinalIgnoreCase)) { //old Mono compilers don't support pdbonly if (monoRuntime != null && !monoRuntime.HasMultitargetingMcs) { debugType = "full"; } } if (!string.Equals(debugType, "none", StringComparison.OrdinalIgnoreCase)) { sb.AppendLine("/debug:" + debugType); } if (compilerParameters.LangVersion != LangVersion.Default) { var langVersionString = CSharpCompilerParameters.TryLangVersionToString(compilerParameters.LangVersion); if (langVersionString == null) { string message = "Invalid LangVersion enum value '" + compilerParameters.LangVersion.ToString() + "'"; monitor.ReportError(message, null); LoggingService.LogError(message); return(null); } sb.AppendLine("/langversion:" + langVersionString); } // mcs default is + but others might not be if (compilerParameters.Optimize) { sb.AppendLine("/optimize+"); } else { sb.AppendLine("/optimize-"); } bool hasWin32Res = !string.IsNullOrEmpty(projectParameters.Win32Resource) && File.Exists(projectParameters.Win32Resource); if (hasWin32Res) { AppendQuoted(sb, "/win32res:", projectParameters.Win32Resource); } if (!string.IsNullOrEmpty(projectParameters.Win32Icon) && File.Exists(projectParameters.Win32Icon)) { if (hasWin32Res) { monitor.ReportWarning("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon."); } else { AppendQuoted(sb, "/win32icon:", projectParameters.Win32Icon); } } if (projectParameters.CodePage != 0) { sb.AppendLine("/codepage:" + projectParameters.CodePage); } else if (runtime is MonoTargetRuntime) { sb.AppendLine("/codepage:utf8"); } if (compilerParameters.UnsafeCode) { sb.AppendLine("-unsafe"); } if (compilerParameters.NoStdLib) { sb.AppendLine("-nostdlib"); } if (!string.IsNullOrEmpty(compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower() != "anycpu") { //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation("Mono.Debugger.Soft", null) == null) { LoggingService.LogWarning("Mono runtime '" + runtime.DisplayName + "' appears to be too old to support the 'platform' C# compiler flag."); } else { sb.AppendLine("/platform:" + compilerParameters.PlatformTarget); } } if (compilerParameters.TreatWarningsAsErrors) { sb.AppendLine("-warnaserror"); if (!string.IsNullOrEmpty(compilerParameters.WarningsNotAsErrors)) { sb.AppendLine("-warnaserror-:" + compilerParameters.WarningsNotAsErrors); } } foreach (var define in configuration.GetDefineSymbols()) { AppendQuoted(sb, "/define:", define); sb.AppendLine(); } CompileTarget ctarget = configuration.CompileTarget; if (!string.IsNullOrEmpty(projectParameters.MainClass)) { sb.AppendLine("/main:" + projectParameters.MainClass); // mcs does not allow providing a Main class when compiling a dll // As a workaround, we compile as WinExe (although the output will still // have a .dll extension). if (ctarget == CompileTarget.Library) { ctarget = CompileTarget.WinExe; } } switch (ctarget) { case CompileTarget.Exe: sb.AppendLine("/t:exe"); break; case CompileTarget.WinExe: sb.AppendLine("/t:winexe"); break; case CompileTarget.Library: sb.AppendLine("/t:library"); break; } foreach (ProjectFile finfo in projectItems.GetAll <ProjectFile> ()) { if (finfo.Subtype == Subtype.Directory) { continue; } switch (finfo.BuildAction) { case "Compile": AppendQuoted(sb, "", finfo.Name); break; case "EmbeddedResource": string fname = finfo.Name; if (string.Compare(Path.GetExtension(fname), ".resx", StringComparison.OrdinalIgnoreCase) == 0) { fname = Path.ChangeExtension(fname, ".resources"); } sb.Append('"'); sb.Append("/res:"); sb.Append(fname); sb.Append(','); sb.Append(finfo.ResourceId); sb.Append('"'); sb.AppendLine(); break; default: continue; } } if (!compilerParameters.DocumentationFile.IsNullOrEmpty) { AppendQuoted(sb, "/doc:", compilerParameters.DocumentationFile); } if (!string.IsNullOrEmpty(compilerParameters.NoWarnings)) { AppendQuoted(sb, "/nowarn:", compilerParameters.NoWarnings); } if (runtime.RuntimeId == "MS.NET") { sb.AppendLine("/fullpaths"); sb.AppendLine("/utf8output"); } string output = ""; string error = ""; File.WriteAllText(responseFileName, sb.ToString()); monitor.Log.WriteLine(compilerName + " /noconfig " + sb.ToString().Replace('\n', ' ')); // Dummy projects created for single files have no filename // and so no BaseDirectory. string workingDir = null; if (configuration.ParentItem != null) { workingDir = configuration.ParentItem.BaseDirectory; } LoggingService.LogInfo(compilerName + " " + sb); ExecutionEnvironment envVars = runtime.GetToolsExecutionEnvironment(project.TargetFramework); string cargs = "/noconfig @\"" + responseFileName + "\""; int exitCode = DoCompilation(monitor, compilerName, cargs, workingDir, envVars, gacRoots, ref output, ref error); BuildResult result = ParseOutput(workingDir, output, error); if (result.CompilerOutput.Trim().Length != 0) { monitor.Log.WriteLine(result.CompilerOutput); } //if compiler crashes, output entire error string if (result.ErrorCount == 0 && exitCode != 0) { try { monitor.Log.Write(File.ReadAllText(error)); } catch (IOException) { } result.AddError("The compiler appears to have crashed. Check the build output pad for details."); LoggingService.LogError("C# compiler crashed. Response file '{0}', stdout file '{1}', stderr file '{2}'", responseFileName, output, error); } else { FileService.DeleteFile(responseFileName); FileService.DeleteFile(output); FileService.DeleteFile(error); } return(result); }
//Rendering IEnumerable <IRenderable> RenderInner(Actor self, WorldRenderer wr) { if (self.World.RenderPlayer != null) { if (self.Owner != self.World.RenderPlayer) { return(Enumerable.Empty <IRenderable>()); } } var render = new HashSet <IRenderable>(); var iz2 = 1 / wr.Viewport.Zoom; var hc2 = Color.LightGray; var ha2 = wr.Screen3DPosition(messageposition); var hb2 = wr.Screen3DPosition(messageposition + new WVec(0, -512, 924)); Game.Renderer.WorldRgbaColorRenderer.DrawLine(ha2, hb2, iz2, hc2); if (GatherLocation != CPos.Zero) { var ha = wr.Screen3DPosition(messageposition); var hb = wr.Screen3DPosition(self.World.Map.CenterOfCell(GatherLocation)); Game.Renderer.WorldRgbaColorRenderer.DrawLine(ha, hb, iz2, Color.Crimson); } if (AttackLocation != null) { var ha = wr.Screen3DPosition(messageposition); var hb = wr.Screen3DPosition(AttackLocation.CenterPosition); Game.Renderer.WorldRgbaColorRenderer.DrawLine(ha, hb, iz2, Color.Crimson); } if (Army.Any() || Commanders.Any() || Utilities.Any()) { var helperx = 0; var helpery = 0; var living = new HashSet <Actor>(); if (Army.Any()) { foreach (var actr in Army) { if (actr != null && !actr.IsDead && actr.IsInWorld) { helperx += actr.CenterPosition.X; helpery += actr.CenterPosition.Y; living.Add(actr); } } } if (Commanders.Any()) { foreach (var actr in Commanders) { if (actr != null && !actr.IsDead && actr.IsInWorld) { helperx += actr.CenterPosition.X; helpery += actr.CenterPosition.Y; living.Add(actr); } } } if (Utilities.Any()) { foreach (var actr in Utilities) { if (actr != null && !actr.IsDead && actr.IsInWorld) { helperx += actr.CenterPosition.X; helpery += actr.CenterPosition.Y; living.Add(actr); } } } if (living.Any()) { helperx /= living.Count; helpery /= living.Count; } var wcr = Game.Renderer.WorldRgbaColorRenderer; foreach (var actr in living) { if (actr != null && !actr.IsDead && actr.IsInWorld) { var iz = 1 / wr.Viewport.Zoom; var hc = Color.LightGray; var ha = wr.Screen3DPosition(actr.CenterPosition); var hb = wr.Screen3DPosition(new WPos(helperx, helpery, 20)); wcr.DrawLine(ha, hb, iz, hc); messageposition = new WPos(helperx, helpery, 20); } } return(render); } return(SpriteRenderable.None); }
/// <summary> /// /// </summary> /// <param name="settings"></param> private void ProcessSucceeded(ZombieSettings settings) { Model.Settings = settings; // (Konrad) Get all allocated assets. They would be allocated if they were // previously deserialized from Settings, or set on previous cycle. var allocated = new HashSet <AssetObject>(); foreach (var l in SourceLocations) { foreach (var a in l.Assets) { allocated.Add(a.Asset); } } Locations = Locations.Where(x => x.LocationObject.LocationType != LocationType.Trash).ToObservableCollection(); foreach (var l in Locations) { foreach (var a in l.Assets) { allocated.Add(a.Asset); } } // (Konrad) Find out if there are any new assets downloaded that were not accounted for. // These would be added to the SourceLocations collection. var added = new HashSet <AssetObject>(); foreach (var a in settings.LatestRelease.Assets) { if (allocated.Contains(a)) { allocated.Remove(a); continue; } added.Add(a); } // (Konrad) Whatever is left in allocated needs to be deleted. var trashLocations = new ObservableCollection <LocationsViewModel>(); foreach (var l in Locations) { var remain = new ObservableCollection <AssetViewModel>(); var trashLoc = new LocationsViewModel(new Location { LocationType = LocationType.Trash, DirectoryPath = l.LocationObject.DirectoryPath }, false); foreach (var avm in l.Assets) { if (!allocated.Contains(avm.Asset)) { remain.Add(avm); } else { if (trashLoc.Assets.Contains(avm)) { continue; } avm.IsPlaceholder = true; trashLoc.Assets.Add(avm); } } l.Assets = remain; trashLocations.Add(trashLoc); } // (Konrad) Let's put these deleted assets into new deleted locations foreach (var lvm in trashLocations) { Locations.Add(lvm); } // (Konrad) If any location is now empty let's remove it. Locations = Locations.Where(x => x.Assets.Any()).ToObservableCollection(); // (Konrad) Add all new assets to source locations. // Since we are calling this from another thread (Timer runs on a thread pool) // we need to make sure that the collection is locked. lock (_sourceLock) { SourceLocations.Clear(); var loc = new LocationsViewModel(new Location { LocationType = LocationType.Source }, !added.Any()); foreach (var asset in added) { var vm = new AssetViewModel(asset) { Parent = loc }; if (!loc.Assets.Contains(vm)) { loc.Assets.Add(vm); } } SourceLocations.Add(loc); } }
private bool HasUnformattedUnary(string expression, HashSet <string> unarys) { return(unarys.Any(unary => Regex.IsMatch(expression, unary + @"(?!\s*\()"))); }