public User(StateManager stateMgr, API.Geo.World world) { this.mStateMgr = stateMgr; this.mWorld = world; this.mTimeSinceGUIOpen = new Timer(); this.mCameraMan = null; this.IsAllowedToMoveCam = true; this.IsFreeCamMode = true; Camera cam = this.mStateMgr.Camera; cam.Position = new Vector3(-203, 633, -183); cam.Orientation = new Quaternion(0.3977548f, -0.1096644f, -0.8781486f, -0.2421133f); this.mCameraMan = new CameraMan(cam); this.mSelectedAllies = new HashSet<VanillaNonPlayer>(); this.mRandom = new Random(); this.mFigures = new MOIS.KeyCode[10]; for (int i = 0; i < 9; i++) this.mFigures[i] = (MOIS.KeyCode)System.Enum.Parse(typeof(MOIS.KeyCode), "KC_" + (i + 1)); this.mFigures[9] = MOIS.KeyCode.KC_0; this.mWireCube = this.mStateMgr.SceneMgr.RootSceneNode.CreateChildSceneNode(); this.mWireCube.AttachObject(StaticRectangle.CreateRectangle(this.mStateMgr.SceneMgr, Vector3.UNIT_SCALE * Cst.CUBE_SIDE)); this.mWireCube.SetVisible(false); this.Inventory = new Inventory(10, 4, new int[] { 3, 0, 1, 2 }, true); }
private void AssignConnectors(DialogueEntry entry, Conversation conversation, HashSet<string> alreadyConnected, HashSet<int> entriesVisited, int level) { // Sanity check to prevent infinite recursion: if (level > 10000) return; // Set non-connectors: foreach (Link link in entry.outgoingLinks) { if (link.originConversationID == link.destinationConversationID) { string destination = string.Format("{0}.{1}", link.destinationConversationID, link.destinationDialogueID); if (alreadyConnected.Contains(destination)) { link.isConnector = true; } else { link.isConnector = false; alreadyConnected.Add(destination); } } } // Then process each child: foreach (Link link in entry.outgoingLinks) { if (link.originConversationID == link.destinationConversationID) { if (!entriesVisited.Contains(link.destinationDialogueID)) { entriesVisited.Add(link.destinationDialogueID); var childEntry = conversation.GetDialogueEntry(link.destinationDialogueID); if (childEntry != null) { AssignConnectors(childEntry, conversation, alreadyConnected, entriesVisited, level + 1); } } } } }
private static void SwapParameterTypes(MethodDefinition method, TypeDefinition targetDependency, TypeReference interfaceType, HashSet<MethodReference> modifiedMethods) { if (method.IsAbstract || !method.HasBody) return; bool modified = false; var parameters = method.Parameters.Cast<ParameterDefinition>(); foreach (var parameter in parameters) { var parameterType = parameter.ParameterType; if (parameterType != targetDependency) continue; parameter.ParameterType = interfaceType; modified = true; } if (!modified) return; modifiedMethods.Add(method); }
internal AnalysisQueue(VsProjectAnalyzer analyzer) { _workEvent = new AutoResetEvent(false); _cancel = new CancellationTokenSource(); _analyzer = analyzer; // save the analysis once it's ready, but give us a little time to be // initialized and start processing stuff... _lastSave = DateTime.Now - _SaveAnalysisTime + TimeSpan.FromSeconds(10); _queue = new List<IAnalyzable>[PriorityCount]; for (int i = 0; i < PriorityCount; i++) { _queue[i] = new List<IAnalyzable>(); } _enqueuedGroups = new HashSet<IGroupableAnalysisProject>(); _workThread = new Thread(Worker); _workThread.Name = "Node.js Analysis Queue"; _workThread.Priority = ThreadPriority.BelowNormal; _workThread.IsBackground = true; // start the thread, wait for our synchronization context to be created using (AutoResetEvent threadStarted = new AutoResetEvent(false)) { _workThread.Start(threadStarted); threadStarted.WaitOne(); } }
public static int Solution2(Stopwatch timer) { timer.Restart(); var a = new HashSet<int>(); int maxlcm = 1; int t = 0; var results = new List<int>(); for (int i = 2; i <= 20; i++) { int k = i%2 == 0 ? 1 : 2; for (int j = k; j < i; j+=2) { if (gcd(i, j) == 1) { a.Add(2*i*(i + j)); } } } var sortedA = a.OrderBy(v => v).ToArray(); while (maxlcm < 1000) { maxlcm = lcm(maxlcm, sortedA[t]); results.Add(maxlcm); t++; } int res = results[results.Count - 2]; timer.Stop(); return res; }
static void Main() { InitializeWordsByChar(); int textLinesCount = int.Parse(Console.ReadLine().ToLower()); for (int i = 0; i < textLinesCount; i++) { GetWords(Console.ReadLine().ToLower()); } int wordsCount = int.Parse(Console.ReadLine()); for (int i = 0; i < wordsCount; i++) { string word = Console.ReadLine(); string wordLowerCase = word.ToLower(); HashSet<string> currentWords = new HashSet<string>(); currentWords.UnionWith(wordsByChar[wordLowerCase[0]]); for (int j = 1; j < wordLowerCase.Length; j++) { currentWords.IntersectWith(wordsByChar[wordLowerCase[j]]); } Console.WriteLine("{0} -> {1}", word, currentWords.Count); } }
private void CollectEntities(int addr, Dictionary<int, Entity> list) { int num = addr; addr = M.ReadInt(addr + 4); var hashSet = new HashSet<int>(); var queue = new Queue<int>(); queue.Enqueue(addr); while (queue.Count > 0) { int nextAddr = queue.Dequeue(); if (hashSet.Contains(nextAddr)) continue; hashSet.Add(nextAddr); if (M.ReadByte(nextAddr + 21) == 0 && nextAddr != num && nextAddr != 0) { int key = M.ReadInt(nextAddr + 12); if (!list.ContainsKey(key)) { int address = M.ReadInt(nextAddr + 16); var entity = base.GetObject<Entity>(address); list.Add(key, entity); } queue.Enqueue(M.ReadInt(nextAddr)); queue.Enqueue(M.ReadInt(nextAddr + 8)); } } }
/// <summary> /// Locates the changes between the prior and post state of the modules.. /// </summary> /// <param name="modules_prior">List of the available modules prior to the update.</param> /// <param name="modules_post">List of the available modules after the update.</param> private void PrintChanges(List<CkanModule> modules_prior, List<CkanModule> modules_post) { var prior = new HashSet<CkanModule>(modules_prior, new NameComparer()); var post = new HashSet<CkanModule>(modules_post, new NameComparer()); var added = new HashSet<CkanModule>(post.Except(prior, new NameComparer())); var removed = new HashSet<CkanModule>(prior.Except(post, new NameComparer())); var unchanged = post.Intersect(prior);//Default compare includes versions var updated = post.Except(unchanged).Except(added).Except(removed).ToList(); // Print the changes. user.RaiseMessage("Found {0} new modules, {1} removed modules and {2} updated modules.", added.Count(), removed.Count(), updated.Count()); if (added.Count > 0) { PrintModules("New modules [Name (CKAN identifier)]:", added); } if (removed.Count > 0) { PrintModules("Removed modules [Name (CKAN identifier)]:", removed); } if (updated.Count > 0) { PrintModules("Updated modules [Name (CKAN identifier)]:", updated); } }
private bool m_useStrict; //= false; #endregion Fields #region Constructors protected JsActivationObject(JsActivationObject parent, JsSettings codeSettings) { m_isKnownAtCompileTime = true; m_useStrict = false; m_settings = codeSettings; Parent = parent; NameTable = new Dictionary<string, JsVariableField>(); ChildScopes = new List<JsActivationObject>(); // if our parent is a scope.... if (parent != null) { // add us to the parent's list of child scopes parent.ChildScopes.Add(this); // if the parent is strict, so are we UseStrict = parent.UseStrict; } // create the two lists of declared items for this scope ScopeLookups = new HashSet<JsLookup>(); VarDeclaredNames = new HashSet<IJsNameDeclaration>(); LexicallyDeclaredNames = new HashSet<IJsNameDeclaration>(); GhostedCatchParameters = new HashSet<JsParameterDeclaration>(); GhostedFunctions = new HashSet<JsFunctionObject>(); }
public override void OnUpdateList () { base.OnUpdateList (); StackFrame frame = DebuggingService.CurrentFrame; if (frame == null || !FrameEquals (frame, lastFrame)) { tree.ClearExpressions (); lastExpressions = null; } lastFrame = frame; if (frame == null) return; //FIXME: tree should use the local refs rather than expressions. ATM we exclude items without names var expr = new HashSet<string> (frame.GetAllLocals ().Select (i => i.Name) .Where (n => !string.IsNullOrEmpty (n) && n != "?")); //add expressions not in tree already, remove expressions that are longer valid if (lastExpressions != null) { foreach (string rem in lastExpressions.Except (expr)) tree.RemoveExpression (rem); foreach (string rem in expr.Except (lastExpressions)) tree.AddExpression (rem); } else { tree.AddExpressions (expr); } lastExpressions = expr; }
public void ModelMetadataProvider_UsesPredicateOnType() { // Arrange var type = typeof(User); var provider = CreateProvider(); var context = new ModelBindingContext(); var expected = new[] { "IsAdmin", "UserName" }; // Act var metadata = provider.GetMetadataForType(type); // Assert var predicate = metadata.PropertyBindingPredicateProvider.PropertyFilter; var matched = new HashSet<string>(); foreach (var property in metadata.Properties) { if (predicate(context, property.PropertyName)) { matched.Add(property.PropertyName); } } Assert.Equal<string>(expected, matched); }
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); } } }
private static IEnumerable<long> Eratostenes() { const int max = 2000000; var primes = new List<long>(); var crossedOff = new HashSet<long>(); long candidate = 1; while (candidate < max) { candidate++; if (crossedOff.Contains(candidate)) { continue; } primes.Add(candidate); // remove multiples of candidate for (var i = candidate; i < max + 1; i += candidate) { crossedOff.Add(i); } } return primes.ToArray(); }
public static H3.Cell[] CalcCells2( Sphere[] mirrors, H3.Cell[] cells, Settings settings ) { HashSet<Vector3D> completedCellIds = new HashSet<Vector3D>( cells.Select( c => c.ID ).ToArray() ); List<H3.Cell> completedCells = new List<H3.Cell>( cells ); ReflectCellsRecursive2( mirrors, cells, settings, completedCells, completedCellIds ); return completedCells.ToArray(); }
private IList<string> DFS(string s, HashSet<string> dict, Dictionary<string, IList<string>> map){ IList<string> matches = new List<string>(); if(s==""){ //Base Case matches.Add(""); return matches; } if(map.ContainsKey(s)) //if s is already in the map, directly return its value return map[s]; int len = s.Length; for(int i=1;i<s.Length+1;i++){ string prev = s.Substring(0,i); if(dict.Contains(prev)){ //if prev is in the dict IList<string> postMatches = DFS(s.Substring(i,len-i),dict,map); foreach(string sentence in postMatches){ if(sentence=="") //if s.Substring(i,len) is empty matches.Add(prev); else matches.Add(prev+" "+sentence); } } } map.Add(s, matches); //after get all matches for s, put the entry into map. return matches; }
public static void Write(TextWriter writer, IEnumerable<Dictionary<string, string>> records) { if (records == null) return; //AOT var allKeys = new HashSet<string>(); var cachedRecords = new List<IDictionary<string, string>>(); foreach (var record in records) { foreach (var key in record.Keys) { if (!allKeys.Contains(key)) { allKeys.Add(key); } } cachedRecords.Add(record); } var headers = allKeys.OrderBy(key => key).ToList(); if (!CsvConfig<Dictionary<string, string>>.OmitHeaders) { WriteRow(writer, headers); } foreach (var cachedRecord in cachedRecords) { var fullRecord = headers.ConvertAll(header => cachedRecord.ContainsKey(header) ? cachedRecord[header] : null); WriteRow(writer, fullRecord); } }
public static IEnumerable<string> GetAllStyleSheets(string searchFrom, IEnumerable<string> allowedExtensions) { var project = ProjectHelpers.GetProject(searchFrom); var projectPath = project.Properties.Item("FullPath").Value.ToString(); var projectUri = new Uri(projectPath, UriKind.Absolute); var fileNames = new HashSet<string>(); var projectDir = Path.GetDirectoryName(projectPath); if (projectDir == null) { return new string[0]; } foreach (var extension in allowedExtensions) { var matchingFiles = Directory.GetFiles(projectDir, "*" + extension, SearchOption.AllDirectories); foreach (var file in matchingFiles) { var mappedFile = GetStyleSheetFileForUrl(file, project, projectUri); if (mappedFile != null) { fileNames.Add(mappedFile); } } } return fileNames; }
internal CoordinatorScratchpad(Type elementType) { _elementType = elementType; _nestedCoordinatorScratchpads = new List<CoordinatorScratchpad>(); _expressionWithErrorHandlingMap = new Dictionary<Expression, Expression>(); _inlineDelegates = new HashSet<LambdaExpression>(); }
public static VTable ConstructVTable(TypeDef typeDef, VTableStorage storage) { var ret = new VTable(typeDef); var slotDict = new Dictionary<VTableSignature, List<VTableSlot>>(); // Partition II 12.2 // Interfaces foreach (InterfaceImpl iface in typeDef.Interfaces) { VTable ifaceVTbl = storage.GetVTable(iface.Interface); if (ifaceVTbl != null) ret.Inherit(ifaceVTbl, slotDict); } // Base type VTable baseVTbl = storage.GetVTable(typeDef.GetBaseTypeThrow()); if (baseVTbl != null) ret.Inherit(baseVTbl, slotDict); List<MethodDef> virtualMethods = typeDef.Methods.Where(method => method.IsVirtual).ToList(); var methodsProcessed = new HashSet<MethodDef>(); // MethodImpls (Partition II 22.27) foreach (MethodDef method in virtualMethods) foreach (MethodOverride impl in method.Overrides) { Debug.Assert(impl.MethodBody == method); MethodDef targetMethod = impl.MethodDeclaration.ResolveThrow(); VTableSignature sig = VTableSignature.FromMethod(impl.MethodDeclaration); Debug.Assert(slotDict.ContainsKey(sig)); var methodSlot = new VTableSlot(ret, method, method.DeclaringType.ToTypeSig(), VTableSignature.FromMethod(method)); ret.Override(slotDict, sig, methodSlot, targetMethod); methodsProcessed.Add(method); } // Normal override foreach (MethodDef method in virtualMethods) { VTableSignature sig = VTableSignature.FromMethod(method); var methodSlot = new VTableSlot(ret, method, method.DeclaringType.ToTypeSig(), sig); if (slotDict.ContainsKey(sig) && slotDict[sig].Count > 0) { ret.Override(slotDict, sig, methodSlot); methodsProcessed.Add(method); } } // Remaining methods foreach (MethodDef method in typeDef.Methods.Where(method => method.IsVirtual).Except(methodsProcessed)) { var slot = new VTableSlot(ret, method, method.DeclaringType.ToTypeSig(), VTableSignature.FromMethod(method)); if (method.IsFinal) ret.Finals.Add(slot); else { Debug.Assert(!ret.Slots.Any(s => s.MethodDef == method)); ret.Slots.Add(slot); } } return ret; }
public Project() { Configuration = new ClientConfiguration(); NotificationSettings = new Dictionary<string, NotificationSettings>(); PromotedTabs = new HashSet<string>(); DeleteBotDataEnabled = true; Data = new DataDictionary(); }
public Conversion ClassifyConversionFromExpression(TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return ClassifyConversionFromExpression(null, source, destination, ref useSiteDiagnostics); }
// admin deletearea x y z radius public override bool HandleCommand(ulong userId, string[] words) { HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesToConfirm = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesConnected = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesFound = new HashSet<IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) continue; IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) continue; bool found = false; foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks) { if (block.TypeId == typeof(MyObjectBuilder_Beacon)) { found = true; break; } } if (!found) entitiesToConfirm.Add(grid); } CubeGrids.GetGridsUnconnected(entitiesFound, entitiesToConfirm); foreach (IMyEntity entity in entitiesFound) { CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(entity.EntityId); if (gridEntity == null) { Log.Info("A found entity gridEntity was null!"); continue; } Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) at {2} with no beacon.", gridEntity.Name, entity.EntityId, General.Vector3DToString(entity.GetPosition()))); } for(int r = entitiesFound.Count - 1; r >= 0; r--) { //MyAPIGateway.Entities.RemoveEntity(entity); IMyEntity entity = entitiesFound.ElementAt(r); CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); gridEntity.Dispose(); } Communication.SendPrivateInformation(userId, string.Format("Removed {0} grids with no beacons", entitiesFound.Count)); return true; }
public static string GenerateText(TypeDeclaration type, OrderedPartCollection<AbstractDynamicCompilationExtension> extensions) { var unit = new CompilationUnit(); var namespaces = new HashSet<string> { typeof (SystemTime).Namespace, typeof (AbstractViewGenerator).Namespace, typeof (Enumerable).Namespace, typeof (IEnumerable<>).Namespace, typeof (IEnumerable).Namespace, typeof (int).Namespace, typeof (LinqOnDynamic).Namespace, typeof(Field).Namespace, }; foreach (var extension in extensions) { foreach (var ns in extension.Value.GetNamespacesToImport()) { namespaces.Add(ns); } } foreach (var ns in namespaces) { unit.AddChild(new Using(ns)); } unit.AddChild(type); var output = new CSharpOutputVisitor(); unit.AcceptVisitor(output, null); return output.Text; }
public Node(string name, FileAttributes attrs) { Attributes = attrs; Name = name; Parents = new HashSet<Node>(); Contains = new HashSet<Node>(); }
private void CreateRandomIndexes(int maxSegments) { dir = NewDirectory(); numDocs = AtLeast(150); int numTerms = TestUtil.NextInt(Random(), 1, numDocs / 5); ISet<string> randomTerms = new HashSet<string>(); while (randomTerms.size() < numTerms) { randomTerms.add(TestUtil.RandomSimpleString(Random())); } terms = new List<string>(randomTerms); int seed = Random().Next(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(new Random(seed))); iwc.SetMergePolicy(TestSortingMergePolicy.NewSortingMergePolicy(sort)); iw = new RandomIndexWriter(new Random(seed), dir, iwc); for (int i = 0; i < numDocs; ++i) { Document doc = RandomDocument(); iw.AddDocument(doc); if (i == numDocs / 2 || (i != numDocs - 1 && Random().nextInt(8) == 0)) { iw.Commit(); } if (Random().nextInt(15) == 0) { string term = RandomInts.RandomFrom(Random(), terms); iw.DeleteDocuments(new Term("s", term)); } } reader = iw.Reader; }
/// <remarks> /// http://stackoverflow.com/questions/730268/unique-random-string-generation /// </remarks> string GenerateRandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") { if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), "length cannot be less than zero."); if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty."); const int byteSize = 0x100; var allowedCharSet = new HashSet<char>(allowedChars).ToArray(); if (byteSize < allowedCharSet.Length) throw new ArgumentException($"allowedChars may contain no more than {byteSize} characters."); // Guid.NewGuid and System.Random are not particularly random. By using a // cryptographically-secure random number generator, the caller is always // protected, regardless of use. using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) { var result = new StringBuilder(); var buf = new byte[128]; while (result.Length < length) { rng.GetBytes(buf); for (var i = 0; i < buf.Length && result.Length < length; ++i) { // Divide the byte into allowedCharSet-sized groups. If the // random value falls into the last group and the last group is // too small to choose from the entire allowedCharSet, ignore // the value in order to avoid biasing the result. var outOfRangeStart = byteSize - (byteSize%allowedCharSet.Length); if (outOfRangeStart <= buf[i]) continue; result.Append(allowedCharSet[buf[i]%allowedCharSet.Length]); } } return result.ToString(); } }
/// <summary> /// Add Hundreds of Stock and Forex Symbol /// </summary> public override void Initialize() { SetStartDate(2001, 10, 07); SetEndDate(2010, 10, 11); SetCash(250000); var allSymbols = StressSymbols.StockSymbols.ToList();//.Concat(ForexSymbols).ToList(); if (TickSymbolsToRun + SecondSymbolsToRun + HourSymbolsToRun + DailySymbolsToRun > allSymbols.Count) { throw new Exception("Too many symbols, all symbols: " + allSymbols.Count); } var hash = new HashSet<string> {"DNY", "MLNK"}; var ticks = GetRandomSymbols(allSymbols, hash, TickSymbolsToRun).ToList(); var seconds = GetRandomSymbols(allSymbols, hash, SecondSymbolsToRun).ToList(); var minutes = GetRandomSymbols(allSymbols, hash, MinuteSymbolsToRun).ToList(); var hours = GetRandomSymbols(allSymbols, hash, HourSymbolsToRun).ToList(); var daily = GetRandomSymbols(allSymbols, hash, DailySymbolsToRun).ToList(); AddSecurity(ticks, Resolution.Tick); AddSecurity(seconds, Resolution.Second); AddSecurity(minutes, Resolution.Minute); AddSecurity(hours, Resolution.Hour); AddSecurity(daily, Resolution.Daily); //SetUniverse(coarse => coarse.Take(1)); }
/// <summary> /// first construct a prime list up to 1k(using seive) /// and check each number after 647 to see if it matches with criteria given by the question /// 1. for each number, first find out all the prime factors, and add them to a hashset /// 2. if prime factors added are not exactly 4, reset the hashset /// 3 (start variable is used to make sure the numbers are continuous, if there is a gap between numbers, reset the hashset) /// 4. if prime factors added are exactly 4, check the hashset count, if it is 16 return the answer /// 5. if it is not 16, continues to next number /// </summary> /// <returns></returns> static int brute_force_test_each_number_for_match() { var max = 1000; //randomly chose, it works :P var bound = (int)Math.Sqrt(max); bool[] primes = new bool[max]; primes[0] = true; primes[1] = true; int s, m; for (s = 2; s <= bound; s++) { if (primes[s] == false) { for (m = s * s; m < max; m += s) { primes[m] = true; } } } var factor = 4; var start = 0; var num = 0; var pwr = 1; var set = new HashSet<int>(); var count = 1; for (s = 647; s < 200000; s++) { num = s; for (m = 2; m < max; m++) { if (primes[m] == false) { pwr = 1; while (num % m == 0) { pwr *= m; num /= m; } if (pwr != 1) set.Add(pwr); if (num <= 1) break; } } if (set.Count == factor * count && (s == start + 1 || start == 0)) { if (count == factor) return s - 3; start = s; count++; } else { set.Clear(); count = 1; start = 0; } } return 0; }
private static void SaveAllConncectedComponents(Node<int> node, HashSet<int> visitedNodes, List<string> connectedComponents) { string graphs = string.Empty; Stack<Node<int>> nodesStack = new Stack<Node<int>>(); nodesStack.Push(node); while (nodesStack.Count > 0) { Node<int> currentNode = nodesStack.Pop(); visitedNodes.Add(currentNode.Value); graphs += " -> " + currentNode.Value; foreach (var child in currentNode.Children) { if (!visitedNodes.Contains(child.Value)) { visitedNodes.Add(child.Value); nodesStack.Push(child); } } } connectedComponents.Add(graphs.Substring(4)); }
private static OrderedMultiDictionary<int, Article> GenerateArticles(int count) { var barcodes = new HashSet<string>(); Console.Write("Generating barcodes..."); while (barcodes.Count < count) { var barcode = RandomGenerator.GetRandomString(BarcodeLength); barcodes.Add(barcode); if (barcodes.Count % (count / 10) == 0) { Console.Write('.'); } } Console.Write("\n\nGenerating articles..."); var articles = new OrderedMultiDictionary<int, Article>(true); foreach (var barcode in barcodes) { var vendor = RandomGenerator.GetRandomString(5); var title = RandomGenerator.GetRandomString(7); var price = RandomGenerator.GeneratRandomNumber(0, count); var article = new Article(barcode, vendor, title, price); articles.Add(price, article); if (articles.Count % (count / 10) == 0) { Console.Write('.'); } } Console.WriteLine(); return articles; }
/* goodG2B() - use goodsource and badsink */ private static void GoodG2B() { int data = CWE789_Uncontrolled_Mem_Alloc__Database_HashSet_61b.GoodG2BSource(); /* POTENTIAL FLAW: Create a HashSet using data as the initial size. data may be very large, creating memory issues */ HashSet <int> intHashSet = new HashSet <int>(data); }
public TipoPagamentoDao() { PedidoTipoPagamentoDao = new HashSet <PedidoTipoPagamentoDao>(); }
public CollectionOfficer() { LeafCollections = new HashSet<LeafCollection>(); SupplierCollections = new HashSet<SupplierCollection>(); CollectionOfficerRoutes = new HashSet<CollectionOfficerRoute>(); }
private long SaveMessageVsReturnsDeviceIds(Request model, int type, string arMessage, NotificationType notificationType, IQueryable <DeviceSetting> devicesList, ref HashSet <string> hashSet) { long messageId = 0; // notification will be sent to users if (type < 4) { messageId = _UnitOfWork.NotificationDeviceRepository.Add(model.UserId, null, notificationType, arMessage, arMessage, model.Id, false); hashSet = new HashSet <string>(devicesList.Where(u => u.DeviceId != null && u.ApplicationUserId == model.UserId && u.ApplicationUser.IsOnline).Select(x => x.DeviceId).Distinct().ToList()); } //notification canceled by admin and notification will be sent to agent and user else if (type == 4) { messageId = _UnitOfWork.NotificationDeviceRepository.Add(model.UserId, model.AgentId, notificationType, arMessage, arMessage, model.Id, false); hashSet = new HashSet <string>(devicesList.Where(u => u.DeviceId != null && u.ApplicationUserId == model.UserId || u.ApplicationUserId == model.AgentId && u.ApplicationUser.IsOnline).Select(x => x.DeviceId).Distinct().ToList()); } // notification will be sent to user when admin delete agent else if (type == 5) { messageId = _UnitOfWork.NotificationDeviceRepository.Add(model.UserId, null, notificationType, arMessage, arMessage, model.Id, false); hashSet = new HashSet <string>(devicesList.Where(u => u.DeviceId != null && u.ApplicationUserId == model.UserId && u.ApplicationUser.IsOnline).Select(x => x.DeviceId).Distinct().ToList()); } //new request and notifications will be sent to all agents suitable to this request if (type == 6) { var agentids = (_repo.GetAllAgent()) .Where(x => (x.Type == (RequestTypesEnum)model.Type || x.Type == RequestTypesEnum.Both) && x.CityId == model.CityId && x.Car.PassengerNumberId >= model.PassengerNumberId && x.IsNotified).Select(u => u.Id).ToList(); messageId = _UnitOfWork.NotificationDeviceRepository.Add(notificationType, arMessage, arMessage, model.Id, agentids, false); hashSet = new HashSet <string>(devicesList.Where(u => u.DeviceId != null && agentids.Contains(u.ApplicationUserId) && u.ApplicationUser.IsOnline && u.ApplicationUser.IsNotified).Select(x => x.DeviceId).Distinct()); } // notification will be sent to agent when user cancel request else if (type == 7) { messageId = _UnitOfWork.NotificationDeviceRepository.Add(model.AgentId, null, notificationType, arMessage, arMessage, model.Id, false); hashSet = new HashSet <string>(devicesList.Where(u => u.DeviceId != null && u.ApplicationUserId == model.AgentId && u.ApplicationUser.IsOnline && u.ApplicationUser.IsNotified).Select(x => x.DeviceId).Distinct()); } else if (type == 9) { messageId = _UnitOfWork.NotificationDeviceRepository.Add(model.AgentId, null, notificationType, arMessage, arMessage, model.Id, false); hashSet = new HashSet <string>(devicesList.Where(u => u.DeviceId != null && u.ApplicationUserId == model.AgentId && u.ApplicationUser.IsOnline && u.ApplicationUser.IsNotified).Select(x => x.DeviceId).Distinct()); } return(messageId); }
public ProductosUsers() { TransaccionesCuentadestinoNavigation = new HashSet<Transacciones>(); TransaccionesCuentaorigenNavigation = new HashSet<Transacciones>(); }
public Majors() { Courses = new HashSet<Courses>(); Students = new HashSet<Students>(); }
public EventByTypeIndexEventFilter(HashSet<string> events) : base(false, events) { _events = events; _streams = new HashSet<string>(from eventType in events select "$et-" + eventType); }
public Decimal CalcTaxableFromTotalAmount( PXCache cache, object row, HashSet<string> taxList, DateTime aDocDate, Decimal aCuryTotal) { IComparer<Tax> taxComparer = GetTaxComparer(); taxComparer.ThrowOnNull(nameof(taxComparer)); Decimal result = Decimal.Zero; PXGraph graph = cache.Graph; Dictionary<string, PXResult<Tax, TaxRev>> taxRates = GetTaxRevisionList(graph, aDocDate); List<PXResult<Tax, TaxRev>> orderedTaxList = new List<PXResult<Tax, TaxRev>>(taxList.Count); foreach (string taxID in taxList) { if (taxRates.TryGetValue(taxID, out PXResult<Tax, TaxRev> line)) { int idx; for (idx = orderedTaxList.Count; (idx > 0) && taxComparer.Compare(orderedTaxList[idx - 1], line) > 0; idx--) ; var tax = (Tax)line; if (_taxCalcMode != null && tax.TaxCalcLevel != CSTaxCalcLevel.CalcOnItemAmtPlusTaxAmt) { switch (_taxCalcMode) { case TaxCalculationMode.Net: tax.TaxCalcLevel = CSTaxCalcLevel.CalcOnItemAmt; break; case TaxCalculationMode.Gross: tax.TaxCalcLevel = CSTaxCalcLevel.Inclusive; break; } } orderedTaxList.Insert(idx, new PXResult<Tax, TaxRev>(tax, (TaxRev)line)); } } Decimal rateInclusive = Decimal.Zero; Decimal rateLvl1 = Decimal.Zero; Decimal rateLvl2 = Decimal.Zero; foreach (PXResult<Tax, TaxRev> iRes in orderedTaxList) { Tax tax = iRes; TaxRev taxRev = iRes; Decimal multiplier = tax.ReverseTax == true ? Decimal.MinusOne : Decimal.One; if (tax.TaxType == CSTaxType.PerUnit) { PXTrace.WriteError(Messages.PerUnitTaxesNotSupportedOperation); throw new PXException(Messages.PerUnitTaxesNotSupportedOperation); } switch (tax.TaxCalcLevel) { case CSTaxCalcLevel.Inclusive: rateInclusive += multiplier * taxRev.TaxRate.Value; break; case CSTaxCalcLevel.CalcOnItemAmt: rateLvl1 += multiplier * taxRev.TaxRate.Value; break; case CSTaxCalcLevel.CalcOnItemAmtPlusTaxAmt: rateLvl2 += multiplier * taxRev.TaxRate.Value; break; } } decimal baseLvl2 = PXDBCurrencyAttribute.RoundCury(cache, row, aCuryTotal / (1 + rateLvl2 / 100), _precision); decimal baseLvl1 = PXDBCurrencyAttribute.RoundCury(cache, row, baseLvl2 / (1 + (rateLvl1 + rateInclusive) / 100), _precision); Decimal curyTaxTotal = decimal.Zero; Decimal curyTax2Total = decimal.Zero; foreach (PXResult<Tax, TaxRev> iRes in orderedTaxList) { Tax tax = iRes; TaxRev taxRev = iRes; Decimal multiplier = tax.ReverseTax == true ? Decimal.MinusOne : Decimal.One; switch (tax.TaxCalcLevel) { case CSTaxCalcLevel.Inclusive: break; case CSTaxCalcLevel.CalcOnItemAmt: curyTaxTotal += multiplier * PXDBCurrencyAttribute.RoundCury(cache, row, (baseLvl1 * taxRev.TaxRate / 100m) ?? 0m, _precision); break; case CSTaxCalcLevel.CalcOnItemAmtPlusTaxAmt: curyTax2Total += multiplier * PXDBCurrencyAttribute.RoundCury(cache, row, (baseLvl2 * taxRev.TaxRate / 100m) ?? 0m, _precision); break; } } result = aCuryTotal - curyTaxTotal - curyTax2Total; return result; }
public void UndoRedo(HashSet <int> layersToRecheck) { Board board; switch (type) { case UndoRedoType.ItemDeleted: //item.Board.BoardItems.Add(item, true); item.InsertItem(); break; case UndoRedoType.ItemAdded: item.RemoveItem(null); break; case UndoRedoType.ItemMoved: XNA.Point oldPos = (XNA.Point)ParamA; item.Move(oldPos.X, oldPos.Y); break; case UndoRedoType.ItemFlipped: ((IFlippable)item).Flip = !((IFlippable)item).Flip; break; case UndoRedoType.LineRemoved: board = ((MapleDot)ParamB).Board; if (ParamC is FootholdLine) { board.BoardItems.FootholdLines.Add((FootholdLine)ParamC); } else if (ParamC is RopeLine) { board.BoardItems.RopeLines.Add((RopeLine)ParamC); } else { throw new Exception("wrong type at undoredo, lineremoved"); } ((MapleLine)ParamC).FirstDot = (MapleDot)ParamA; ((MapleLine)ParamC).SecondDot = (MapleDot)ParamB; ((MapleDot)ParamA).connectedLines.Add((MapleLine)ParamC); ((MapleDot)ParamB).connectedLines.Add((MapleLine)ParamC); break; case UndoRedoType.LineAdded: board = ((MapleDot)ParamB).Board; if (ParamC is FootholdLine) { board.BoardItems.FootholdLines.Remove((FootholdLine)ParamC); } else if (ParamC is RopeLine) { board.BoardItems.RopeLines.Remove((RopeLine)ParamC); } else { throw new Exception("wrong type at undoredo, lineadded"); } ((MapleLine)ParamC).Remove(false, null); break; case UndoRedoType.ToolTipLinked: ((ToolTipInstance)item).CharacterToolTip = null; ((ToolTipChar)ParamA).BoundTooltip = null; break; case UndoRedoType.ToolTipUnlinked: ((ToolTipChar)ParamA).BoundTooltip = (ToolTipInstance)item; break; case UndoRedoType.BackgroundMoved: ((BackgroundInstance)item).BaseX = ((XNA.Point)ParamA).X; ((BackgroundInstance)item).BaseY = ((XNA.Point)ParamA).Y; break; case UndoRedoType.ItemsLinked: item.ReleaseItem((BoardItem)ParamA); break; case UndoRedoType.ItemsUnlinked: item.BindItem((BoardItem)ParamA, (Microsoft.Xna.Framework.Point)ParamB); break; case UndoRedoType.ItemsLayerChanged: InputHandler.ClearSelectedItems(((BoardItem)((List <IContainsLayerInfo>)ParamC)[0]).Board); foreach (IContainsLayerInfo layerInfoItem in (List <IContainsLayerInfo>)ParamC) { layerInfoItem.LayerNumber = (int)ParamA; } ((BoardItem)((List <IContainsLayerInfo>)ParamC)[0]).Board.Layers[(int)ParamA].RecheckTileSet(); ((BoardItem)((List <IContainsLayerInfo>)ParamC)[0]).Board.Layers[(int)ParamB].RecheckTileSet(); break; case UndoRedoType.ItemLayerPlatChanged: Tuple <int, int> oldLayerPlat = (Tuple <int, int>)ParamA; Tuple <int, int> newLayerPlat = (Tuple <int, int>)ParamB; IContainsLayerInfo li = (IContainsLayerInfo)ParamC; li.LayerNumber = oldLayerPlat.Item1; li.PlatformNumber = oldLayerPlat.Item2; layersToRecheck.Add(oldLayerPlat.Item1); layersToRecheck.Add(newLayerPlat.Item1); break; case UndoRedoType.RopeAdded: ((Rope)ParamA).Remove(null); break; case UndoRedoType.RopeRemoved: ((Rope)ParamA).Create(); break; case UndoRedoType.ItemZChanged: item.Z = (int)ParamA; item.Board.BoardItems.Sort(); break; case UndoRedoType.VRChanged: //TODO break; case UndoRedoType.MapCenterChanged: //TODO break; case UndoRedoType.LayerTSChanged: string ts_old = (string)ParamA; string ts_new = (string)ParamB; Layer l = (Layer)ParamC; l.ReplaceTS(ts_old); break; case UndoRedoType.zMChanged: int zm_old = (int)ParamA; int zm_new = (int)ParamB; IContainsLayerInfo target = (IContainsLayerInfo)ParamC; target.PlatformNumber = zm_old; break; } }
public Produkt() { MatrattProdukt = new HashSet<MatrattProdukt>(); }
public Library() { Library_Book = new HashSet<Library_Book>(); }
public void AddErrors(DocumentId key, HashSet <DiagnosticData> diagnostics) => AddErrors(_documentMap, key, diagnostics);
public void VerifyAnalyzeNodeCalledForAllSyntaxKinds(HashSet<TLanguageKindEnum> syntaxKindsPatterns) { var expectedSyntaxKinds = AllSyntaxKinds.Where(IsAnalyzeNodeSupported); var actualSyntaxKinds = _callLog.Where(a => FilterByAbstractName(a, "SyntaxNode")).Select(e => e.SyntaxKind).Concat(syntaxKindsPatterns).Distinct(); AssertIsSuperset(expectedSyntaxKinds, actualSyntaxKinds); }
private void CalculatePassengerMovement(Vector3 velocity) { HashSet<Transform> movedPassengers = new HashSet<Transform>(); passengerMovement = new List<PassengerMovement>(); float directionX = Mathf.Sign(velocity.x); float directionY = Mathf.Sign(velocity.y); /*Vertically moving platform*/ if (velocity.y != 0) { float rayLength = Mathf.Abs(velocity.y) + skinWidth; for (int i = 0; i < verticalRayCount; i++) { Vector2 rayOrigin = directionY == -1 ? raycastOrigins.bottomLeft : raycastOrigins.topLeft; rayOrigin += Vector2.right * (verticalRaySpacing * i); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, passengerMask); /*hit.distance checks if the player is inside the platform*/ if (hit && hit.distance != 0) { if (!movedPassengers.Contains(hit.transform)) { float pushX = directionY == 1 ? velocity.x : 0; float pushY = velocity.y - (hit.distance - skinWidth) * directionY; passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), directionY == 1, true)); movedPassengers.Add(hit.transform); } } } } /*Horizontally moving platform*/ if (velocity.x != 0) { float rayLength = Mathf.Abs(velocity.x) + skinWidth; for (int i = 0; i < horizontalRayCount; i++) { Vector2 rayOrigin = directionX == -1 ? raycastOrigins.bottomLeft : raycastOrigins.bottomRight; rayOrigin += Vector2.up * (horizontalRaySpacing * i); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, passengerMask); if (hit && hit.distance != 0) { if (!movedPassengers.Contains(hit.transform)) { float pushX = velocity.x - (hit.distance - skinWidth) * directionX; float pushY = -skinWidth; passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), false, true)); movedPassengers.Add(hit.transform); } } } } /*Passenger is on top of horizontally moving platform*/ if(directionY == -1 || velocity.y == 0 && velocity.x != 0) { float rayLength = skinWidth * 2; for (int i = 0; i < verticalRayCount; i++) { Vector2 rayOrigin = raycastOrigins.topLeft + Vector2.right * (verticalRaySpacing * i); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up, rayLength, passengerMask); if (hit && hit.distance != 0) { if (!movedPassengers.Contains(hit.transform)) { float pushX = velocity.x; float pushY = velocity.y - (hit.distance - skinWidth) * directionY; passengerMovement.Add(new PassengerMovement(hit.transform, new Vector3(pushX, pushY), true, false)); movedPassengers.Add(hit.transform); } } } } }
public StudentSubject() { ExamSubject = new HashSet<ExamSubject>(); }
public override void Bad() { int data = CWE789_Uncontrolled_Mem_Alloc__Database_HashSet_61b.BadSource(); /* POTENTIAL FLAW: Create a HashSet using data as the initial size. data may be very large, creating memory issues */ HashSet <int> intHashSet = new HashSet <int>(data); }
public Employees() { EmployeeTerritories = new HashSet <EmployeeTerritories>(); InverseReportsToNavigation = new HashSet <Employees>(); Orders = new HashSet <Orders>(); }
public Employees() { Employees1 = new HashSet <Employees>(); Orders = new HashSet <Orders>(); Territories = new HashSet <Territories>(); }
public Account() { Composition = new HashSet <Composition>(); }
public User() { Report = new HashSet <Report>(); }
public Product() { OrderDetails = new HashSet<OrderDetail>(); }
/// <inheritdoc /> public override void OnInspectorGUI() { this.DrawDefaultInspector(); var gameDataAsset = (Object)this.target; var gameDataPath = FileAndPathUtils.MakeProjectRelative(AssetDatabase.GetAssetPath(gameDataAsset)); var assetPath = FileAndPathUtils.MakeProjectRelative(AssetDatabase.GetAssetPath(Selection.activeObject)); if (GameDataTracker.IsGameDataFile(assetPath) == false) { return; } if (this.lastAsset != gameDataAsset || this.gameDataSettings == null) { this.gameDataSettings = GameDataSettings.Load(gameDataPath); this.gameDataSettings.ScriptingAssemblies = this.gameDataSettings.ScriptingAssemblies ?? new string[0]; this.lastAsset = gameDataAsset; this.newScriptingAssembly = null; this.newScriptingAssemblyName = null; } GUI.enabled = true; GUILayout.Label(Path.GetFileName(gameDataPath), EditorStyles.boldLabel); this.gameDataSettings.Generator = (int)(GameDataSettings.CodeGenerator)EditorGUILayout.EnumPopup(Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_GENERATOR, (GameDataSettings.CodeGenerator)this.gameDataSettings.Generator); if (this.gameDataSettings.Generator != (int)GameDataSettings.CodeGenerator.None) { this.codeGenerationFold = EditorGUILayout.Foldout(this.codeGenerationFold, Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_GENERATION_LABEL); if (this.codeGenerationFold) { this.gameDataSettings.AutoGeneration = EditorGUILayout.Toggle(Resources.UI_UNITYPLUGIN_INSPECTOR_AUTO_GENERATION, this.gameDataSettings.AutoGeneration); var codeAsset = !string.IsNullOrEmpty(this.gameDataSettings.CodeGenerationPath) && File.Exists(this.gameDataSettings.CodeGenerationPath) ? AssetDatabase.LoadAssetAtPath<TextAsset>(this.gameDataSettings.CodeGenerationPath) : null; var assetAsset = !string.IsNullOrEmpty(this.gameDataSettings.AssetGenerationPath) && File.Exists(this.gameDataSettings.AssetGenerationPath) ? AssetDatabase.LoadAssetAtPath<ScriptableObject>(this.gameDataSettings.AssetGenerationPath) : null; if (codeAsset != null) this.gameDataSettings.CodeGenerationPath = AssetDatabase.GetAssetPath(EditorGUILayout.ObjectField(Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_GENERATION_PATH, codeAsset, typeof(TextAsset), false)); else this.gameDataSettings.CodeGenerationPath = EditorGUILayout.TextField(Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_GENERATION_PATH, this.gameDataSettings.CodeGenerationPath); if (this.gameDataSettings.Generator == (int)GameDataSettings.CodeGenerator.CSharpCodeAndAsset) { if (assetAsset != null) this.gameDataSettings.AssetGenerationPath = AssetDatabase.GetAssetPath(EditorGUILayout.ObjectField(Resources.UI_UNITYPLUGIN_INSPECTOR_ASSET_GENERATION_PATH, assetAsset, typeof(ScriptableObject), false)); else this.gameDataSettings.AssetGenerationPath = EditorGUILayout.TextField(Resources.UI_UNITYPLUGIN_INSPECTOR_ASSET_GENERATION_PATH, this.gameDataSettings.AssetGenerationPath); } if ((this.gameDataSettings.Generator == (int)GameDataSettings.CodeGenerator.CSharp || this.gameDataSettings.Generator == (int)GameDataSettings.CodeGenerator.CSharpCodeAndAsset) && Path.GetExtension(this.gameDataSettings.CodeGenerationPath) != ".cs") this.gameDataSettings.CodeGenerationPath = Path.ChangeExtension(this.gameDataSettings.CodeGenerationPath, ".cs"); if (this.gameDataSettings.Generator == (int)GameDataSettings.CodeGenerator.CSharpCodeAndAsset && Path.GetExtension(this.gameDataSettings.AssetGenerationPath) != ".asset") this.gameDataSettings.AssetGenerationPath = Path.ChangeExtension(this.gameDataSettings.AssetGenerationPath, ".asset"); this.gameDataSettings.Namespace = EditorGUILayout.TextField(Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_NAMESPACE, this.gameDataSettings.Namespace); this.gameDataSettings.GameDataClassName = EditorGUILayout.TextField(Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_API_CLASS_NAME, this.gameDataSettings.GameDataClassName); this.gameDataSettings.DocumentClassName = EditorGUILayout.TextField(Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_DOCUMENT_CLASS_NAME, this.gameDataSettings.DocumentClassName); this.gameDataSettings.LineEnding = (int)(GameDataSettings.LineEndings)EditorGUILayout.EnumPopup( Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_LINE_ENDINGS, (GameDataSettings.LineEndings)this.gameDataSettings.LineEnding); this.gameDataSettings.Indentation = (int)(GameDataSettings.Indentations)EditorGUILayout.EnumPopup( Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_INDENTATION, (GameDataSettings.Indentations)this.gameDataSettings.Indentation); this.gameDataSettings.Options = (int)(CodeGenerationOptions)EditorGUILayout.EnumMaskField( Resources.UI_UNITYPLUGIN_INSPECTOR_CODE_OPTIONS, (CodeGenerationOptions)this.gameDataSettings.Options); } } this.scriptingAssembliesFold = EditorGUILayout.Foldout(this.scriptingAssembliesFold, Resources.UI_UNITYPLUGIN_INSPECTOR_SCRIPTING_ASSEMBLIES_LABEL); if (this.scriptingAssembliesFold) { for (var i = 0; i < this.gameDataSettings.ScriptingAssemblies.Length; i++) { var watchedAssetPath = this.gameDataSettings.ScriptingAssemblies[i]; var assetExists = !string.IsNullOrEmpty(watchedAssetPath) && (File.Exists(watchedAssetPath) || Directory.Exists(watchedAssetPath)); var watchedAsset = assetExists ? AssetDatabase.LoadMainAssetAtPath(watchedAssetPath) : null; if (watchedAsset != null) this.gameDataSettings.ScriptingAssemblies[i] = AssetDatabase.GetAssetPath(EditorGUILayout.ObjectField(Resources.UI_UNITYPLUGIN_INSPECTOR_ASSET_LABEL, watchedAsset, typeof(Object), false)); else this.gameDataSettings.ScriptingAssemblies[i] = EditorGUILayout.TextField(Resources.UI_UNITYPLUGIN_INSPECTOR_NAME_LABEL, watchedAssetPath); } EditorGUILayout.Space(); this.newScriptingAssembly = EditorGUILayout.ObjectField("<" + Resources.UI_UNITYPLUGIN_INSPECTOR_ADD_ASSET_BUTTON + ">", this.newScriptingAssembly, typeof(Object), false); if (Event.current.type == EventType.repaint && this.newScriptingAssembly != null) { var assemblies = new HashSet<string>(this.gameDataSettings.ScriptingAssemblies); assemblies.Remove(""); assemblies.Add(AssetDatabase.GetAssetPath(this.newScriptingAssembly)); this.gameDataSettings.ScriptingAssemblies = assemblies.ToArray(); this.newScriptingAssembly = null; GUI.changed = true; } EditorGUILayout.BeginHorizontal(); this.newScriptingAssemblyName = EditorGUILayout.TextField("<" + Resources.UI_UNITYPLUGIN_INSPECTOR_ADD_NAME_BUTTON + ">", this.newScriptingAssemblyName); if (GUILayout.Button(Resources.UI_UNITYPLUGIN_INSPECTOR_ADD_BUTTON, EditorStyles.toolbarButton, GUILayout.Width(70), GUILayout.Height(18))) { var assemblies = new HashSet<string>(this.gameDataSettings.ScriptingAssemblies); assemblies.Remove(""); assemblies.Add(this.newScriptingAssemblyName); this.gameDataSettings.ScriptingAssemblies = assemblies.ToArray(); this.newScriptingAssemblyName = null; GUI.changed = true; this.Repaint(); } GUILayout.Space(5); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); GUILayout.Label(Resources.UI_UNITYPLUGIN_INSPECTOR_ACTIONS_GROUP, EditorStyles.boldLabel); if (EditorApplication.isCompiling) EditorGUILayout.HelpBox(Resources.UI_UNITYPLUGIN_COMPILING_WARNING, MessageType.Warning); else if (CoroutineScheduler.IsRunning) EditorGUILayout.HelpBox(Resources.UI_UNITYPLUGIN_COROUTINE_IS_RUNNIG_WARNING, MessageType.Warning); EditorGUILayout.BeginHorizontal(); GUI.enabled = !CoroutineScheduler.IsRunning && !EditorApplication.isCompiling; if (GUILayout.Button(Resources.UI_UNITYPLUGIN_INSPECTOR_EDIT_BUTTON)) { AssetDatabase.OpenAsset(gameDataAsset); this.Repaint(); } if (this.gameDataSettings.Generator != (int)GameDataSettings.CodeGenerator.None && string.IsNullOrEmpty(this.gameDataSettings.CodeGenerationPath) == false) { if (GUILayout.Button(Resources.UI_UNITYPLUGIN_INSPECTOR_RUN_GENERATOR_BUTTON)) { CoroutineScheduler.Schedule(Menu.GenerateCodeAndAssetsAsync(gameDataPath, ProgressUtils.ReportToLog(Resources.UI_UNITYPLUGIN_INSPECTOR_GENERATION_PREFIX + " ")), "generation::" + gameDataPath) .ContinueWith(_ => this.Repaint()); } } GUI.enabled = !CoroutineScheduler.IsRunning && !EditorApplication.isCompiling; if (GUILayout.Button(Resources.UI_UNITYPLUGIN_INSPECTOR_VALIDATE_BUTTON)) { CoroutineScheduler.Schedule(Menu.ValidateAsync(gameDataPath, ProgressUtils.ReportToLog(Resources.UI_UNITYPLUGIN_INSPECTOR_VALIDATION_PREFIX + " ")), "validation::" + gameDataPath) .ContinueWith(_ => this.Repaint()); } if (GUILayout.Button(Resources.UI_UNITYPLUGIN_INSPECTOR_BACKUP_BUTTON)) { this.Backup(gameDataPath); } if (GUILayout.Button(Resources.UI_UNITYPLUGIN_INSPECTOR_RESTORE_BUTTON)) { this.Restore(gameDataPath); } EditorGUILayout.EndHorizontal(); GUI.enabled = true; if (GUI.changed) { this.gameDataSettings.Save(gameDataPath); } }
public User() { Tweets = new HashSet <Tweet>(); }
public Supplier() { Phones = new HashSet<Phone>(); }
public void AddErrors(ProjectId key, HashSet <DiagnosticData> diagnostics) => AddErrors(_projectMap, key, diagnostics);
public OrderLineItem() { Configurations = new HashSet<ProductConfiguration>(); }
public Cocept() { Relations relations = new Relations(); Console.WriteLine("Матрица смежности:"); for (int i = 0; i < relations.size; i++) { for (int j = 0; j < relations.size; j++) { Console.Write(relations.matrix[i, j] + " "); } Console.WriteLine(); } HashSet <List <int> > crossing = new HashSet <List <int> >(); for (int i = 0; i < relations.size; i++) { List <int> tempCrossing = new List <int>(); for (int j = 0; j < relations.size; j++) { if (relations.matrix[j, i] == 1) { tempCrossing.Add(j + 1); } } crossing.Add(tempCrossing); } while (true) { int flag = crossing.Count(); for (int i = 0; i < crossing.Count; i++) { for (int j = i + 1; j < crossing.Count; j++) { List <int> tempCrossing = new List <int>(); foreach (var item in crossing.ElementAt(i)) { if (crossing.ElementAt(j).Contains(item)) { tempCrossing.Add(item); } } bool flag2 = true; for (int l = 0; l < crossing.Count; l++) { if (tempCrossing.Count == crossing.ElementAt(l).Count) { for (int t = 0; t < crossing.ElementAt(l).Count; t++) { if (!(crossing.ElementAt(l).Contains(tempCrossing[t]))) { break; } flag2 = false; } } } if (flag2) { if (tempCrossing.Count == 0) { if (!(crossing.ElementAt(crossing.Count - 1).Count == 0)) { crossing.Add(tempCrossing); } } else { crossing.Add(tempCrossing); } } } } if (flag == crossing.Count()) { break; } } List <int> allElement = new List <int>(); for (int i = 1; i < relations.size; i++) { allElement.Add(i); } bool flag4 = true; for (int l = 0; l < crossing.Count; l++) { if (allElement.Count == crossing.ElementAt(l).Count) { for (int t = 0; t < crossing.ElementAt(l).Count; t++) { if (!(crossing.ElementAt(l).Contains(allElement[t]))) { break; } flag4 = false; } } } if (flag4) { crossing.Add(allElement); } List <List <List <int> > > neighbours = new List <List <List <int> > >(); for (int i = 0; i < crossing.Count; i++) { neighbours.Add(new List <List <int> >()); for (int j = 0; j < crossing.Count; j++) { bool flag = true; if (i != j) { for (int k = 0; k < crossing.ElementAt(i).Count; k++) { if (!(crossing.ElementAt(j).Contains(crossing.ElementAt(i)[k]))) { flag = false; break; } } } if (flag && i != j) { neighbours.ElementAt(i).Add(crossing.ElementAt(j)); } } } //идем по всем пересечениям for (int i = 0; i < crossing.Count; i++) { List <List <int> > temp = new List <List <int> >(neighbours.ElementAt(i)); //по соседям пересечения for (int j = 0; j < temp.Count; j++) { //ищем номер соседа в пересечении int numb = 0; for (int n = 0; n < crossing.Count; n++) { if (crossing.ElementAt(n).Count == temp[j].Count) { bool flag = true; for (int l = 0; l < crossing.ElementAt(n).Count; l++) { if (!(crossing.ElementAt(n)[l] == temp[j][l])) { flag = false; break; } } if (flag) { numb = n; break; } } } for (int n = 0; n < neighbours.ElementAt(numb).Count; n++) { if (temp.Contains(neighbours.ElementAt(numb)[n])) { neighbours.ElementAt(i).Remove(neighbours.ElementAt(numb)[n]); } } } } List <List <List <int> > > levels = new List <List <List <int> > >(); levels.Add(neighbours.ElementAt(neighbours.Count - 1)); bool flag3 = true; while (flag3) { levels.Add(new List <List <int> >()); for (int i = 0; i < levels.ElementAt(levels.Count - 2).Count; i++) { int numb = 0; for (int n = 0; n < crossing.Count; n++) { if (crossing.ElementAt(n).Count == levels.ElementAt(levels.Count - 2)[i].Count) { bool flag = true; for (int l = 0; l < crossing.ElementAt(n).Count; l++) { if (!(crossing.ElementAt(n)[l] == levels.ElementAt(levels.Count - 2)[i][l])) { flag = false; break; } } if (flag) { numb = n; break; } } } for (int j = 0; j < neighbours.ElementAt(numb).Count; j++) { if (!(levels[levels.Count - 1].Contains(neighbours.ElementAt(numb)[j]))) { levels[levels.Count - 1].Add(neighbours.ElementAt(numb)[j]); if (neighbours.ElementAt(numb)[j].Count == relations.size) { flag3 = false; } } } } } string alph = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < levels.Count; i++) { Console.WriteLine("{0} уровень:", i); foreach (var item in levels[i]) { List <int> temp = new List <int>(); Console.Write("{"); foreach (var num in item) { Console.Write(num + " "); temp.Add(num); } Console.Write("}"); Console.Write("{"); for (int j = 0; j < relations.size; j++) { bool flag = true; for (int j2 = 0; j2 < temp.Count; j2++) { if (relations.matrix[temp[j2] - 1, j] == 0) { flag = false; } } if (flag) { Console.Write(alph.ElementAt(j) + " "); } } Console.Write("}"); } Console.WriteLine(); } int index = 0; foreach (var item in crossing) { Console.Write("{"); foreach (var num in item) { Console.Write(num + " "); } Console.Write("}:"); foreach (var neigb in neighbours[index]) { Console.Write("{"); foreach (var num in neigb) { Console.Write(num + " "); } Console.Write("}"); } Console.WriteLine(); index++; } }
public Autores() { Livros = new HashSet<Livros>(); }
public Illustration() { ProductModelIllustrations = new HashSet<ProductModelIllustration>(); }
public Vacancy() { SkillRequirements = new HashSet<SkillRequirement>(); VacancyCities = new HashSet<VacancyCity>(); CVs = new HashSet<VacancyCVFlow>(); }