public static CombinedSequence GetCombinedSequence(string seq1, string seq2) { List<CombinedSequence> scores = new List<CombinedSequence>(); for (int i = 0; i < 3; i++) { List<int> vs = new List<int>(); for (int j = 0; j < i; j++) { vs.Add(j); } var subseq1 = seq1.Substring(i); scores.Add(new CombinedSequence() { Sequence1 = seq1, Sequence2 = seq2, Position1 = i, Position2 = 0, MismatchPositions = vs.Union(GetMismatchIndecies(subseq1, seq2).ConvertAll(m => m + i)).ToArray() }); var subseq2 = seq2.Substring(i); scores.Add(new CombinedSequence() { Sequence1 = seq1, Sequence2 = seq2, Position1 = 0, Position2 = i, MismatchPositions = vs.Union(GetMismatchIndecies(seq1, subseq2).ConvertAll(m => m + i)).ToArray() }); } var min = scores.Min(m => m.MismatchPositions.Length); return scores.Find(m => m.MismatchPositions.Length == min); }
public ActionResult GetPendingTrans() { var WF = new BusinessLogic.FFWorkFlow(); IEnumerable<KeyValuePair<int, string>> trans = new List<KeyValuePair<int,string>>(); if (User.IsInRole("administrators") || User.IsInRole("sales")) trans = trans.Union(WF.GetTranForSales()); if (User.IsInRole("administrators") || User.IsInRole("operation")) trans = trans.Union(WF.GetTranForOperations()); if (User.IsInRole("administrators") || User.IsInRole("accounting")) trans = trans.Union(WF.GetTranForAccounting()); if (User.IsInRole("administrators") || User.IsInRole("customersservice") || User.IsInRole("accounting")) trans = trans.Union(WF.GetTranToBePaid()); if (User.IsInRole("administrators") || User.IsInRole("customersservice") || User.IsInRole("operation")) trans = trans.Union(WF.GetTranETA()); if (trans == null) { return Json(null, JsonRequestBehavior.AllowGet); } return Json(trans, JsonRequestBehavior.AllowGet); }
public SiteExport(Guid siteID, ExportType exportWhat) { SiteData s = null; List<ContentPageExport> pages = new List<ContentPageExport>(); s = SiteData.GetSiteByID(siteID); if (exportWhat == ExportType.AllData) { pages = ContentImportExportUtils.ExportAllSiteContent(siteID); } else { if (exportWhat == ExportType.ContentData) { List<ContentPageExport> lst = ContentImportExportUtils.ExportPages(siteID); pages = pages.Union(lst).ToList(); } if (exportWhat == ExportType.BlogData) { List<ContentPageExport> lst = ContentImportExportUtils.ExportPosts(siteID); pages = pages.Union(lst).ToList(); } } this.TheUsers = (from u in ExtendedUserData.GetUserList() select new SiteExportUser { Email = u.Email, Login = u.UserName, FirstName = u.FirstName, LastName = u.LastName, UserNickname = u.UserNickName }).ToList(); SetVals(s, pages); }
public IEnumerable<Member> GetAlltimeChatMembers(Chat chat) { IEnumerable<string> participants = new List<string>(); participants = participants.Union(chat.Participants.Split(' ')); participants = participants.Union(chat.ActiveMembers.Split(' ')); participants = participants.Union(chat.Posters.Split(' ')); var members = LoadMembers(participants); return members; }
public override IList<string> GetUsedTypes() { var returnList = new List<string>(); returnList = returnList.Union(GetUsedTypesFromAstNodes(Body)).ToList(); returnList = returnList.Union(GetUsedTypesFromInputElements(ExceptionTypes)).ToList(); return returnList; }
/// <summary> /// Accessor for all of the critical nodes in the tree. /// </summary> /// <returns>a list of the critical nodes in the tree</returns> public List<TreeNode> GetCritical() { List<TreeNode> list = new List<TreeNode>(); list = list.Union(this.parentless).ToList(); list = list.Union(this.childless ).ToList(); list = list.Union(this.merging ).ToList(); return list; }
public override IList<string> GetUsedTypes() { var returnList = new List<string>(); returnList = returnList.Union(GetUsedTypesFromAstNodes(Body)).ToList(); returnList = returnList.Union(GetUsedTypesFromAstNodes(Condition)).ToList(); return returnList; }
public override IList<string> GetUsedTypes() { var returnList = new List<string>(); returnList = returnList.Union(GetUsedTypesFromAstNodes(AssignedValue)).ToList(); returnList = returnList.Union(GetUsedTypesFromInputElements(Modifiers)).ToList(); AddUsedTypeIfIdentifierToken(VariableType, returnList); return returnList; }
public static IEnumerable<Type> GetImplementingTypes(Type typeToImplement) { Assembly asm = Assembly.GetExecutingAssembly(); List<Type> ret = new List<Type>(); ret = ret.Union(GetImplementingTypesInAssembly(typeToImplement, asm)).ToList(); asm = Assembly.GetCallingAssembly(); if (asm != null) ret = ret.Union(GetImplementingTypesInAssembly(typeToImplement, asm)).ToList(); return ret; }
private List <T> GetUnionOfListsOfObjects <T>(List <T> listOne, List <T> listTwo, IEqualityComparer <T> equalityComparer = null) { if (listOne != null) { listTwo = equalityComparer != null ? listTwo?.Union(listOne, equalityComparer).ToList() : listTwo?.Union(listOne).ToList(); } return(listTwo?.Count == 0 ? null : listTwo); }
public override IList<string> GetUsedTypes() { var returnList = new List<string>(); returnList = returnList.Union(GetUsedTypesFromAstNodes(TryBody)).ToList(); returnList = returnList.Union(GetUsedTypesFromAstNodes(FinallyBody)).ToList(); foreach (var catchStatement in CatchStatements) { returnList = returnList.Union(catchStatement.GetUsedTypes()).ToList(); } return returnList; }
public override IList<string> GetUsedTypes() { var returnList = new List<string>(); returnList = returnList.Union(GetUsedTypesFromAstNodes(Condition)).ToList(); returnList = returnList.Union(GetUsedTypesFromAstNodes(Body)).ToList(); returnList = returnList.Union(GetUsedTypesFromAstNodes(ElseBody)).ToList(); foreach (var conditionalElse in ConditionalElses) { returnList = returnList.Union(conditionalElse.GetUsedTypes()).ToList(); } return returnList; }
public override IList<string> GetUsedTypes() { var returnList = new List<string>(); foreach (var argument in Arguments) { returnList = returnList.Union(argument.GetUsedTypes()).ToList(); } AddUsedTypeIfIdentifierToken(ReturnType, returnList); returnList = returnList.Union(GetUsedTypesFromAstNodes(Body)).ToList(); AddUsedTypeIfIdentifierToken(ThrowsType, returnList); return returnList; }
public static string[] GetReferences(MonoIsland island, string projectDirectory) { List<string> list = new List<string>(); List<string> first = new List<string>(); IEnumerator<string> enumerator = first.Union<string>(island._references).GetEnumerator(); try { while (enumerator.MoveNext()) { string current = enumerator.Current; string fileName = Path.GetFileName(current); if (string.IsNullOrEmpty(fileName) || (!fileName.Contains("UnityEditor.dll") && !fileName.Contains("UnityEngine.dll"))) { string file = !Path.IsPathRooted(current) ? Path.Combine(projectDirectory, current) : current; if (AssemblyHelper.IsManagedAssembly(file) && !AssemblyHelper.IsInternalAssembly(file)) { list.Add(file); } } } } finally { if (enumerator == null) { } enumerator.Dispose(); } return list.ToArray(); }
public AlbumsViewModel(User user, Group group) { GroupAlbums = new List<AlbumViewModel>(); UserAlbums = new List<AlbumViewModel>(); CreateGroupAlbum = new AlbumCreateEditViewModel(); CreateUserAlbum = new AlbumCreateEditViewModel(); if (group != null) { GroupId = group.Id; GroupAlbums = group.Albums.Select(x => new AlbumViewModel(x)).ToList(); CreateGroupAlbum = new AlbumCreateEditViewModel(group); } if (user != null) { UserId = user.Id; UserAlbums = user.Albums.Select(x => new AlbumViewModel(x)).ToList(); CreateUserAlbum = new AlbumCreateEditViewModel(user); } Albums = GroupAlbums.Union(UserAlbums).ToList(); }
public void TestAverageVertexes() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; var selPl1 = ed.GetEntity("Pl1"); if (selPl1.Status != PromptStatus.OK) return; var selPl2 = ed.GetEntity("Pl2"); if (selPl2.Status != PromptStatus.OK) return; using (var t = db.TransactionManager.StartTransaction()) { var pl1 = selPl1.ObjectId.GetObject(OpenMode.ForWrite) as Polyline; var pl2 = selPl2.ObjectId.GetObject(OpenMode.ForWrite) as Polyline; pl1.AverageVertexes(ref pl2, new Autodesk.AutoCAD.Geometry.Tolerance(1, 1)); var pls = new List<Polyline> { pl1, pl2 }; var plUnion = pls.Union(null); EntityHelper.AddEntityToCurrentSpace(plUnion); t.Commit(); } }
static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (var i = 0; i < ' '; i++) escapeChars.Add((char) i); foreach (var escapeChar in escapeChars.Union(new[] {'\''})) SingleQuoteCharEscapeFlags[escapeChar] = true; foreach (var escapeChar in escapeChars.Union(new[] {'"'})) DoubleQuoteCharEscapeFlags[escapeChar] = true; foreach (var escapeChar in escapeChars.Union(new[] {'"', '\'', '<', '>', '&'})) HtmlCharEscapeFlags[escapeChar] = true; }
public List<InsurancePolicy> RefreshPolicies(List<InsurancePolicy> currentPolicies) { if (OnRefreshPolicies != null) OnRefreshPolicies(); return currentPolicies.Union(_insuranceInfos).ToList(); }
protected virtual List<int> GetAvailableTransitions(TreeNode node) { List<int> tSet = new List<int>(); for (int i = 0; i < node.Marking.rows; i++) { if (node.Marking[i] > 0) { tSet = tSet.Union(GetPostPSet(i, (int)node.Marking[i])).ToList(); } } List<int> tRes = new List<int>(); for (int i = 0; i < tSet.Count; i++) { bool available = true, dead = true; for (int p = 0; p < PetriNet.PlacesCount; p++) { if (PetriNet.WeightMatrix[p, tSet[i]] != null && PetriNet.WeightMatrix[p, tSet[i]].PT > 0 && PetriNet.WeightMatrix[p, tSet[i]].PT > node.Marking[p]) { available = false; } //if (PetriNet.WeightMatrix[p, tSet[i]] != null && PetriNet.WeightMatrix[p, tSet[i]].TP > 0) //{ // dead = false; //} } if (available )//&& !dead) tRes.Add(tSet[i]); } return tRes; }
private Entities.Models.ForumTopic GetLastTopicOfForum(long id) { var forum = _forumRepository.Get(id); var topics = new List<Entities.Models.ForumTopic>(); forum.Children.ForEach(a => topics.AddRange(a.Topics)); return topics.Union(forum.Topics).OrderByDescending(a => a.CreateDate).FirstOrDefault(); }
private async Task<ShipmentQuantity> TotalQuantityReceived(Guid importNotificationId, Shipment shipment) { await authorization.EnsureAccessAsync(importNotificationId); var movements = await context.ImportMovements.Where(m => m.NotificationId == importNotificationId).ToArrayAsync(); var allMovementReceipts = new List<ImportMovementReceipt>(); foreach (var movement in movements) { var movementReceipts = await context.ImportMovementReceipts.Where(mr => mr.MovementId == movement.Id).ToListAsync(); allMovementReceipts = allMovementReceipts.Union(movementReceipts).ToList(); } if (!allMovementReceipts.Any()) { return new ShipmentQuantity(0, shipment == null ? ShipmentQuantityUnits.Tonnes : shipment.Quantity.Units); } var totalReceived = allMovementReceipts.Sum(m => ShipmentQuantityUnitConverter.ConvertToTarget( m.Unit, shipment.Quantity.Units, m.Quantity)); return new ShipmentQuantity(totalReceived, shipment.Quantity.Units); }
public static void Test() { List<Person> personList1 = new List<Person>(){new Person(){Id = 2,IsMale = true, Height = 178.5, Name = null}}; List<Person> personList2 = new List<Person>() { new Person() { Id = 3, IsMale = true, Height = 178.5, Name = "Test2" } }; var list = personList1.Union(personList2).ToArray(); Console.WriteLine(list[0].Name); }
public override void Execute(ServiceBusConfiguration configuration) { var factoryTypes = new List<Type>(); ReflectionService.GetAssemblies(AppDomain.CurrentDomain.BaseDirectory).ForEach(assembly => factoryTypes.AddRange(ReflectionService.GetTypes<IQueueFactory>(assembly))); foreach (var type in factoryTypes.Union(ReflectionService.GetTypes<IQueueFactory>())) { try { type.AssertDefaultConstructor(string.Format(Resources.DefaultConstructorRequired, "Queue factory", type.FullName)); var instance = (IQueueFactory)Activator.CreateInstance(type); if (!configuration.Queues.ContainsQueueFactory(instance.Scheme)) { configuration.Queues.RegisterQueueFactory(instance); } } catch (Exception ex) { Log.Warning(string.Format("Queue factory not instantiated: {0}", ex.Message)); } } }
public void ActivateToolBarItems() { IEnumerable<string> activeKeys = new List<string>(); _menuClients.ToList().ForEach(item => activeKeys = activeKeys.Union(item.GetActiveMenuKeys(MingApp.Instance.GetCurrentTreeViewItem()))); foreach (var bar in _toolBarTray.ToolBars) { foreach (var item in bar.Items) { var button = item as Button; if (button != null) { if (activeKeys.Contains(button.Name)) { button.Opacity = 1.0; button.IsEnabled = true; } else { button.Opacity = 0.4; button.IsEnabled = false; } } } } }
public ActionResult SidebarMenu() { //获取第一层菜单 //var model = new List<SideBarMenuModel>(); //var parentMenus = _permissionService.GetAllPermissionsByParentId(0).Select(t => // new SideBarMenuModel // { // Name = t.Name, // Area = t.Area, // Controller = t.Controller, // Action = t.Action // } // ).ToList(); //model.AddRange(parentMenus); //SortMenuForTree(model, parentMenus); //return PartialView(model); //var currentUser = _workContextService.CurrentUser; var currentUser = _userService.GetUserById(1); var permissions = new List<Permission> { }; var rolePermissions = currentUser.Roles.Select(t => t.Permissions).ToList(); foreach (var rp in rolePermissions) { permissions = permissions.Union(rp).ToList(); } var model = SortMenuForTree(0, permissions); return PartialView(model); }
static void Main(string[] args) { Console.WriteLine("Enter anything but int to exit.\r\n"); while (true) { int pad = 18; List<int> inputNumbers = new List<int>(); List<int> addThose = new List<int>(); try { Console.Write("Enter numbers: ".PadLeft(pad)); inputNumbers = Array.ConvertAll(Console.ReadLine().Split(' '), i => int.Parse(i)).ToList(); Console.Write("numbers to add: ".PadLeft(pad)); addThose = Array.ConvertAll(Console.ReadLine().Split(' '), i => int.Parse(i)).ToList(); } catch (Exception) { return; } List<int> outputSorted = inputNumbers.Union(addThose).ToList(); outputSorted.Sort(); Console.Write("Result: ".PadLeft(pad)); Console.WriteLine(string.Join(" ", outputSorted.ToArray())); Console.WriteLine(new string('-', pad)); } }
public ActionResult DealerList(int id) { var area = db.Area.First(a => a.Id == id); var root = Area.CreateTree(db.Area.ToArray(), area); List<Dealer> dealers = new List<Dealer>(); if (!root.HasChildren) { dealers = root.Data.Dealers.ToList(); } else { foreach (var a in root.Leafs) { dealers = dealers.Union(a.Data.Dealers).ToList(); } } List<Dictionary<string, object>> jdealers = new List<Dictionary<string, object>>(); foreach (var d in dealers) { var obj = ClassHelper.ToDictionary(d, "Id", "Address", "Contact", "Tel", "Mobile", "Fax", "Website", "Zipcode", "latitude", "longitude"); obj.Add("Name", d.MyArea.Name); jdealers.Add(obj); } return Json(new { dealers = jdealers }, JsonRequestBehavior.AllowGet); }
public static List<SalesHistoryData> GetSalesHistory() { List<SalesHistoryData> result = new List<SalesHistoryData>(); try { // The encrypted list will timeout for slightly large lists (in the hundreds), so the list is // being grabbed in smaller chunks. Transaction logic is used to lock the list while the list is being // grabbed. TransactionOptions transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = IsolationLevel.RepeatableRead; transactionOptions.Timeout = new TimeSpan(0, 2, 0); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions)) { Console.WriteLine("Test 1: List all Sales Orders"); int take = 5; int count = UserSession.Current.Client.GetSalesOrderListCount(); for (int skip = 0; skip < count; skip = skip + take) { List<SalesHistoryData> salesOrders = UserSession.Current.Client.GetSalesHistory(take, skip).ToList(); result = result.Union(salesOrders).ToList(); } result = result.OrderByDescending(so => so.SalesOrderNumber).ThenBy(so => so.SortOrder).ToList(); //No scope.Complete here as no write tasks are being scoped. scope.Dispose(); } } catch (Exception) { throw; } return result; }
public void Union() { var Orwells = new List<string> { "1984", "Animal Farm", "Homage to Catalonia", "Burmese Days" }; var great_novels = new List<string> { "Hear of Darkness", "1984", "Animal Farm", "Ulysses" }; var all = great_novels.Union(Orwells).ToList(); Assert.Equal(all, FILL_ME_IN); }
public ActionResult Province(string name) { var province = db.Area.First(a => a.Name == name); var root = Area.CreateTree(db.Area.ToArray(), province); List<Dealer> dealers = new List<Dealer>(); foreach (var a in root.Leafs) { dealers = dealers.Union(a.Data.Dealers).ToList(); } List<Dictionary<string, object>> jdealers = new List<Dictionary<string, object>>(); foreach (var d in dealers) { var obj = ClassHelper.ToDictionary(d, "Id", "Name", "Address", "Contact", "Tel", "Mobile", "Fax", "Website", "Zipcode", "latitude", "longitude"); jdealers.Add(obj); } var children = province.Children.ToList(); List<Dictionary<string, object>> cities = new List<Dictionary<string, object>>(); foreach (var c in children) { cities.Add(ClassHelper.ToDictionary(c, "Id", "ParentId", "Name")); } return Json(new { id = province.Id, dealers = jdealers, cities = cities }, JsonRequestBehavior.AllowGet); }
public static List<GeneradorDeNumero> GenerarComplementos(List<int> excluidos) { var posibles = digitos.Except(excluidos); var variaciones = new Variations<int>(posibles, 4); return variaciones.Select(variacion => new GeneradorDeNumero(variacion[0], variacion[1], variacion[2], variacion[3], excluidos.Union(variacion).ToList())).ToList(); }
public void Analyze(Solution theSolutionToAnalyze) { foreach (var project in theSolutionToAnalyze.Projects) { foreach (var document in project.Documents) { SyntaxTree currentSyntaxTree = document.GetSyntaxTreeAsync().Result; var foo = 1; //CSharpUnitTestLintWalker walker = // new CSharpUnitTestLintWalker(violations) // { // CurrentProject = project.Name, // CurrentSourceCodeFileName = document.Name // }; // Our walker assumes that its SyntaxNode is an entire source code file. // Therefore, our visitor requires that the SyntaxNode's IsCompilationUnit // attribute is true. We know that it is true, because we pass // an entirely parsed source code file. //walker.Visit((CompilationUnitSyntax)currentSyntaxTree.GetRoot()); //enhancedDiagnostics = enhancedDiagnostics.Union(walker.EnhancedDiagnostics).ToList(); //numberOfTestsFound += walker.NumberOfTestsFound; //numberOfTestsWithIssues += walker.NumberOfTestsWithIssues; } } IUnitTestsViolations violations = new UnitTestViolations(); IList <EnhancedDiagnostic> enhancedDiagnostics = new List <EnhancedDiagnostic>(); int numberOfTestsFound = 0; int numberOfTestsWithIssues = 0; foreach (var project in theSolutionToAnalyze.Projects) { foreach (var document in project.Documents) { SyntaxTree currentSyntaxTree = document.GetSyntaxTreeAsync().Result; CSharpUnitTestLintWalker walker = new CSharpUnitTestLintWalker(violations) { CurrentProject = project.Name, CurrentSourceCodeFileName = document.Name }; // Our walker assumes that its SyntaxNode is an entire source code file. // Therefore, our visitor requires that the SyntaxNode's IsCompilationUnit // attribute is true. We know that it is true, because we pass // an entirely parsed source code file. walker.Visit((CompilationUnitSyntax)currentSyntaxTree.GetRoot()); enhancedDiagnostics = enhancedDiagnostics.Union(walker.EnhancedDiagnostics).ToList(); numberOfTestsFound += walker.NumberOfTestsFound; numberOfTestsWithIssues += walker.NumberOfTestsWithIssues; } } var violationsByIdAndSeverity = enhancedDiagnostics .GroupBy(ed => ed.Diag.Id + " - " + ed.Severity) .Select(group => new { group.Key, Count = group.Count() }) .OrderByDescending(edgrp => edgrp.Count); var topTestsWithIssues = enhancedDiagnostics .GroupBy(ed => ed.MethodName) .Select(group => new { MethodName = group.Key, Count = group.Count() }) .OrderByDescending(newGroups => newGroups.Count) .Take(10); // TODO: Do not hard code this. The walker should return a collection. Console.WriteLine("Rules Used In Analysis:"); Console.WriteLine(" SRLCDUTL002: An 'if' statement found in a test."); Console.WriteLine(" SRLCDUTL003: A 'foreach' statement found in a test."); Console.WriteLine(" SRLCDUTL004: A 'magic number' found in a test."); Console.WriteLine(" SRLCDUTL005: A 'try / catch statement' found in a test."); Console.WriteLine(" SRLCDUTL006: A 'for loop statement' found in a test."); Console.WriteLine(" SRLCDUTL007: A 'while loop statement' found in a test."); Console.WriteLine(" SRLCDUTL008: An 'ternary operator statement' found in a test."); Console.WriteLine(); Console.WriteLine("Number of tests found: {0}", numberOfTestsFound); Console.WriteLine(); Console.WriteLine("Number of issues found: {0}", enhancedDiagnostics.Count); Console.WriteLine(); Console.WriteLine("Number of tests with issues: {0} - {1}%", numberOfTestsWithIssues, numberOfTestsWithIssues / numberOfTestsFound); Console.WriteLine(); Console.WriteLine("Violations by Rule And Severity:"); foreach (var violationGroup in violationsByIdAndSeverity) { Console.WriteLine(" {0} : {1}", violationGroup.Key, violationGroup.Count); } Console.WriteLine(); Console.WriteLine("Top Ten Tests By Violations Count:"); // TODO: Magic Numbers seems to be reporting violation counts incorrectly. // See Content Manager - // Execute_ReturnsCorrectValues_IfColumnTypesContainsColumnsThatShouldBeStripped foreach (var methodWithIssues in topTestsWithIssues) { Console.WriteLine(" {0} : {1}", methodWithIssues.MethodName, methodWithIssues.Count); } Console.WriteLine(); Console.WriteLine("----------------------------------------"); Console.WriteLine(); Console.WriteLine("Violations Details:"); Console.WriteLine(); Console.WriteLine("----------------------------------------"); foreach (EnhancedDiagnostic enhancedDiag in enhancedDiagnostics) { Console.WriteLine("Project Name - {0}:", enhancedDiag.ProjectName); Console.WriteLine("File Name - {0} ", enhancedDiag.SourceCodeFileName); Console.WriteLine("Test Method Name - {0} ", enhancedDiag.MethodName); Console.WriteLine("Rule violation:"); Console.WriteLine(" ID - {0}:", enhancedDiag.Diag.Id); Console.WriteLine(" Severity - {0} ", enhancedDiag.Diag.Severity); Console.WriteLine(" Title - {0} ", enhancedDiag.Diag.Descriptor.Title); Console.WriteLine(" Message - {0} ", enhancedDiag.Diag.GetMessage()); Console.WriteLine(" Source - {0} ", enhancedDiag.CodeViolationSnippet); Console.WriteLine(); Console.WriteLine("----------------------------------------"); Console.WriteLine(); } }
private string ProjectText(MonoIsland island, SolutionSynchronizer.Mode mode, string allAssetsProject) { StringBuilder stringBuilder = new StringBuilder(this.ProjectHeader(island)); List <string> first = new List <string>(); List <Match> matchList = new List <Match>(); bool isBuildingEditorProject = island._output.EndsWith("-Editor.dll"); foreach (string file1 in island._files) { string lower = Path.GetExtension(file1).ToLower(); string file2 = !Path.IsPathRooted(file1) ? Path.Combine(this._projectDirectory, file1) : file1; if (".dll" != lower) { string str = "Compile"; stringBuilder.AppendFormat(" <{0} Include=\"{1}\" />{2}", (object)str, (object)this.EscapedRelativePathFor(file2), (object)SolutionSynchronizer.WindowsNewline); } else { first.Add(file2); } } stringBuilder.Append(allAssetsProject); foreach (string str1 in first.Union <string>((IEnumerable <string>)island._references)) { if (!str1.EndsWith("/UnityEditor.dll") && !str1.EndsWith("/UnityEngine.dll") && (!str1.EndsWith("\\UnityEditor.dll") && !str1.EndsWith("\\UnityEngine.dll"))) { Match match = SolutionSynchronizer.scriptReferenceExpression.Match(str1); if (match.Success && (mode == SolutionSynchronizer.Mode.UnityScriptAsUnityProj || (int)Enum.Parse(typeof(ScriptingLanguage), match.Groups["language"].Value, true) == 2)) { matchList.Add(match); } else { string str2 = !Path.IsPathRooted(str1) ? Path.Combine(this._projectDirectory, str1) : str1; if (AssemblyHelper.IsManagedAssembly(str2) && (!AssemblyHelper.IsInternalAssembly(str2) || SolutionSynchronizer.IsInternalAssemblyThatShouldBeReferenced(isBuildingEditorProject, str2))) { string path = str2.Replace("\\", "/").Replace("\\\\", "/"); stringBuilder.AppendFormat(" <Reference Include=\"{0}\">{1}", (object)Path.GetFileNameWithoutExtension(path), (object)SolutionSynchronizer.WindowsNewline); stringBuilder.AppendFormat(" <HintPath>{0}</HintPath>{1}", (object)path, (object)SolutionSynchronizer.WindowsNewline); stringBuilder.AppendFormat(" </Reference>{0}", (object)SolutionSynchronizer.WindowsNewline); } } } } if (0 < matchList.Count) { stringBuilder.AppendLine(" </ItemGroup>"); stringBuilder.AppendLine(" <ItemGroup>"); using (List <Match> .Enumerator enumerator = matchList.GetEnumerator()) { while (enumerator.MoveNext()) { Match current = enumerator.Current; string str = current.Groups["project"].Value; stringBuilder.AppendFormat(" <ProjectReference Include=\"{0}{1}\">{2}", (object)str, (object)SolutionSynchronizer.GetProjectExtension((ScriptingLanguage)Enum.Parse(typeof(ScriptingLanguage), current.Groups["language"].Value, true)), (object)SolutionSynchronizer.WindowsNewline); stringBuilder.AppendFormat(" <Project>{{{0}}}</Project>", (object)this.ProjectGuid(Path.Combine("Temp", current.Groups["project"].Value + ".dll")), (object)SolutionSynchronizer.WindowsNewline); stringBuilder.AppendFormat(" <Name>{0}</Name>", (object)str, (object)SolutionSynchronizer.WindowsNewline); stringBuilder.AppendLine(" </ProjectReference>"); } } } stringBuilder.Append(this.ProjectFooter(island)); return(stringBuilder.ToString()); }
protected override void FilterInitialize() { if (_filterInitialized) { return; } _filterInitialized = true; _filters = (IList <Filter>)HttpContext.Current.Items["MyProducts.FiltersCache"]; if (Page == null && _filters != null) { _filterHandlers = _filters. Union(_filters.SelectMany(r => r.AllChildren)). Where(p => p.FilterHandler != null). ToDictionary(p => LinqFilterGenerator.GetFilterName(p.FilterName)); return; } BrowseFilterParameters parameters; IList <Filter> filters = new List <Filter>(); var stack = new Stack <IList <Filter> >(); _filters = filters; Filter current; BaseFilterParameter currentBF = null; //колонка 'Наименование' current = currentBF = new BaseFilterParameterString <MyProduct>(r => r.Name) { FilterName = "Name", Header = MyProductsResources.Name__Header, IsJournalFilter = true, Mandatory = true, Type = FilterHtmlGenerator.FilterType.Text, MaxLength = 200, Width = "98%", }; currentBF.AddFilter(filters); //filters.Add(current); //колонка 'Дата создания' current = currentBF = new BaseFilterParameter <MyProduct, DateTime>(r => r.CreationDate) { FilterName = "CreationDate", Header = MyProductsResources.CreationDate__Header, IsJournalFilter = true, Mandatory = true, Type = FilterHtmlGenerator.FilterType.Numeric, IsDateTime = true, }; currentBF.AddFilter(filters); //filters.Add(current); //колонка 'Цена' current = currentBF = new BaseFilterParameter <MyProduct, Decimal>(r => r.Price) { FilterName = "Price", Header = MyProductsResources.Price__Header, IsJournalFilter = true, Mandatory = true, Type = FilterHtmlGenerator.FilterType.Numeric, DecimalPrecision = 2, MaxLength = 8, Columns = 8, }; currentBF.AddFilter(filters); //filters.Add(current); //колонка 'Доступно' current = currentBF = new BaseFilterParameter <MyProduct, Decimal>(r => r.Amount) { FilterName = "Amount", Header = MyProductsResources.Amount__Header, IsJournalFilter = true, Mandatory = true, Type = FilterHtmlGenerator.FilterType.Numeric, DecimalPrecision = 2, MaxLength = 8, Columns = 8, }; currentBF.AddFilter(filters); //filters.Add(current); if (Url.IsMultipleSelect) { current = new Filter { FilterName = MultipleSelectedValues, Header = TableResources.MultipleSelectedFilterHeader, Type = FilterHtmlGenerator.FilterType.Boolean, TrueBooleanText = TableResources.MultipleSelectedFilterSelected, FalseBooleanText = TableResources.MultipleSelectedFilterNotSelected, Mandatory = true, FilterHandler = delegate(IQueryable enumerable, Enum type, string value1, string value2) { throw new Exception("Is not actual delegate"); }, }; filters.Add(current); } AddSearchFilter(filters); SetDefaultFilterType(filters); FilterInitialize(filters); if (CustomFilter != null && !_customFiltersInitialized) { _customFiltersInitialized = true; InitializeCustomFilters(filters); } _filterHandlers = filters. Union(filters.SelectMany(r => r.AllChildren)). Where(p => p.FilterHandler != null). ToDictionary(p => LinqFilterGenerator.GetFilterName(p.FilterName)); HttpContext.Current.Items["MyProducts.FiltersCache"] = filters; }
public async Task <List <Event> > SearchByCategory(string search, int type) { var list = new List <IEnumerable <DAL.App.DTO.Event> >(); switch (type) { case 1: return((await Uow.Event.FindByEventNameSearch(search)).Select(item => EventMapper.MapFromDAL(item)).ToList()); break; case 2: list = await Uow.Event.FindByAdministrativeUnitSearch(search); break; case 3: list = await Uow.Event.FindByEventTypeSearch(search); break; case 4: list = await Uow.Event.FindByLocationSearch(search); break; case 5: list = await Uow.Event.FindByTargetAudienceSearch(search); break; case 6: list = await Uow.Event.FindByLocationSearch(search); break; case 7: list = await Uow.Event.FindByOrganizationSearch(search); break; case 8: list = await Uow.Event.FindBySponsorSearch(search); break; case 9: list = await Uow.Event.FindByPerformerSearch(search); break; } var union = new List <DAL.App.DTO.Event>(); foreach (var t in list) { union = new List <DAL.App.DTO.Event>(union.Union(t, new EventComparer())); } return(union.Select(item => EventMapper.MapFromDAL(item)).ToList()); }
/// <summary> /// Generate a simple Polygon and then triangulate it. /// The Result is then Displayed. /// </summary> /// <param name="sender">The Sender (i.e. the Button)</param> /// <param name="e">The routet Event Args</param> private void generatePolygonButton_Click(object sender, RoutedEventArgs e) { // Generate random Polygon var random = new Random(); var cnt = mViewModel.PointCount; mPolygonPoints = new List <Vector2>(); var angle = 0f; var angleDiff = 2f * (Single)Math.PI / cnt; var radius = 4f; // Random Radii for the Polygon var radii = new List <float>(); var innerRadii = new List <float>(); for (int i = 0; i < cnt; i++) { radii.Add(random.NextFloat(radius * 0.9f, radius * 1.1f)); innerRadii.Add(random.NextFloat(radius * 0.2f, radius * 0.3f)); } var hole1 = new List <Vector2>(); var hole2 = new List <Vector2>(); var holeDistance = 2f; var holeAngle = random.NextFloat(0, (float)Math.PI * 2); var cos = (float)Math.Cos(holeAngle); var sin = (float)Math.Sin(holeAngle); var offset1 = new Vector2(holeDistance * cos, holeDistance * sin); var offset2 = new Vector2(-holeDistance * cos, -holeDistance * sin); for (int i = 0; i < cnt; i++) { // Flatten a bit var radiusUse = radii[i]; mPolygonPoints.Add(new Vector2(radii[i] * (Single)Math.Cos(angle), radii[i] * (Single)Math.Sin(angle))); hole1.Add(offset1 + new Vector2(innerRadii[i] * (Single)Math.Cos(-angle), innerRadii[i] * (Single)Math.Sin(-angle))); hole2.Add(offset2 + new Vector2(innerRadii[i] * (Single)Math.Cos(-angle), innerRadii[i] * (Single)Math.Sin(-angle))); angle += angleDiff; } var holes = new List <List <Vector2> >() { hole1, hole2 }; // Triangulate and measure the Time needed for the Triangulation var before = DateTime.Now; var sLTI = SweepLinePolygonTriangulator.Triangulate(mPolygonPoints, holes); var after = DateTime.Now; // Generate the Output var geometry = new HelixToolkit.Wpf.SharpDX.MeshGeometry3D(); geometry.Positions = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); geometry.Normals = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); foreach (var point in mPolygonPoints.Union(holes.SelectMany(h => h))) { geometry.Positions.Add(new Vector3(point.X, 0, point.Y + 5)); geometry.Normals.Add(new Vector3(0, 1, 0)); } geometry.Indices = new HelixToolkit.Wpf.SharpDX.Core.IntCollection(sLTI); triangulatedPolygon.Geometry = geometry; var lb = new LineBuilder(); for (int i = 0; i < sLTI.Count; i += 3) { lb.AddLine(geometry.Positions[sLTI[i]], geometry.Positions[sLTI[i + 1]]); lb.AddLine(geometry.Positions[sLTI[i + 1]], geometry.Positions[sLTI[i + 2]]); lb.AddLine(geometry.Positions[sLTI[i + 2]], geometry.Positions[sLTI[i]]); } mViewModel.LineGeometry = lb.ToLineGeometry3D(); // Set the Lines if activated if (mViewModel.ShowTriangleLines) { lineTriangulatedPolygon.Geometry = mViewModel.LineGeometry; } else { lineTriangulatedPolygon.Geometry = null; } // Set the InfoLabel Text var timeNeeded = (after - before).TotalMilliseconds; infoLabel.Content = String.Format("Last triangulation of {0} Points took {1:0.##} Milliseconds!", triangulatedPolygon.Geometry.Positions.Count, timeNeeded); }
static List <int> UseUnion(List <int> Aage, List <int> Bage) { return(Aage.Union(Bage).ToList()); }
public static double CaculateRebalanceCost(List <string> ETFs, List <string> ETFs_holding, double[] ETFs_holding_allocation, DataPreProcessing preprocessing) { var Expected_Allocation = PO.ETF2AllocationOwnOptim(ETFs, preprocessing); double rebalance = 0; var Union_ETFs = ETFs.Union(ETFs_holding).ToArray(); double[] Lastweek = new double[Union_ETFs.Count()]; double[] Thisweek = new double[Union_ETFs.Count()]; for (int j = 0; j < Union_ETFs.Count(); j++) { Lastweek[j] = 0; for (int i = 0; i < ETFs_holding.Count(); i++) { if (ETFs_holding[i] == Union_ETFs[j]) { Lastweek[j] = ETFs_holding_allocation[i]; } else { continue; } } } for (int j = 0; j < Union_ETFs.Count(); j++) { Thisweek[j] = 0; for (int i = 0; i < ETFs.Count(); i++) { if (ETFs[i] == Union_ETFs[j]) { Thisweek[j] = Expected_Allocation[i]; } else { continue; } } } for (int i = 0; i < Union_ETFs.Count(); i++) { rebalance += Math.Abs(Thisweek[i] - Lastweek[i]); } double rebalance_cost = rebalance * 0.05; Console.WriteLine("Rebalance Cost is {0}", rebalance_cost); return(rebalance_cost); }
protected void Page_Load(object sender, EventArgs e) { using (ISiteNavHelper navHelper = SiteNavFactory.GetSiteNavHelper()) { string sCurrentPage = SiteData.CurrentScriptName; string sScrubbedURL = SiteData.AlternateCurrentScriptName; if (sScrubbedURL.ToLower() != sCurrentPage.ToLower()) { sCurrentPage = sScrubbedURL; } ContentPage currentPage = pageHelper.FindByFilename(SiteData.CurrentSiteID, sCurrentPage); if (currentPage == null && SiteData.IsPageReal) { IsPageTemplate = true; } if ((SiteData.IsPageSampler || IsPageTemplate) && currentPage == null) { currentPage = ContentPageHelper.GetSamplerView(); } litVersion.Text = SiteData.CarrotCakeCMSVersion; litRelease.Text = currentPage.GoLiveDate.ToString(); litRetire.Text = currentPage.RetireDate.ToString(); litTemplate.Text = currentPage.TemplateFile; CurrentPageID = currentPage.Root_ContentID; lnkCurrent.HRef = SiteData.CurrentScriptName; EditPageURL = SiteFilename.PageAddEditURL; PageIndexURL = SiteFilename.PageIndexURL; if (currentPage.ContentType == ContentPageType.PageType.BlogEntry) { EditPageURL = SiteFilename.BlogPostAddEditURL; PageIndexURL = SiteFilename.BlogPostIndexURL; } if (!IsPostBack) { List <SiteNav> nav = navHelper.GetChildNavigation(SiteData.CurrentSiteID, CurrentPageID, !SecurityData.IsAuthEditor); SiteNav pageContents2 = navHelper.GetParentPageNavigation(SiteData.CurrentSiteID, CurrentPageID); if (pageContents2 != null) { pageContents2.NavMenuText = "Parent: " + pageContents2.NavMenuText; pageContents2.NavOrder = -110; lnkParent.Visible = true; lnkParent.HRef = pageContents2.FileName; } else { lnkParent.Visible = false; } ContentPage homePage = pageHelper.FindHome(SiteData.CurrentSiteID); List <SiteNav> lstNavTop = null; if (homePage != null && homePage.Root_ContentID == CurrentPageID) { lstNavTop = (from n in navHelper.GetTopNavigation(SiteData.CurrentSiteID, !SecurityData.IsAuthEditor) where n.Root_ContentID != CurrentPageID orderby n.NavOrder select new SiteNav { NavOrder = n.NavOrder, FileName = n.FileName, NavMenuText = (n.NavOrder > 0 ? " -- " : "") + n.FileName + " [[" + (n.PageActive ? "" : "{*U*} ") + n.NavMenuText + "]]", PageActive = n.PageActive, ContentID = n.ContentID, Root_ContentID = n.Root_ContentID, PageHead = n.PageHead, SiteID = n.SiteID }).ToList(); } List <SiteNav> lstNav = (from n in nav orderby n.NavOrder select new SiteNav { NavOrder = n.NavOrder, FileName = n.FileName, NavMenuText = (n.NavOrder > 0 ? " -- " : "") + n.FileName + " [[" + (n.PageActive ? "" : "{*U*} ") + n.NavMenuText + "]]", PageActive = n.PageActive, ContentID = n.ContentID, Root_ContentID = n.Root_ContentID, PageHead = n.PageHead, SiteID = n.SiteID }).ToList(); if (lstNavTop != null) { lstNav = lstNavTop.Union(lstNav).ToList(); } GeneralUtilities.BindListDefaultText(ddlCMSLinks, lstNav, null, "Navigate", "00000"); if (lstNav.Count < 1) { ddlCMSLinks.Visible = false; lblChildDDL.Visible = false; } } } }
string ProjectText(Assembly assembly, Dictionary <string, string> allAssetsProjectParts, IEnumerable <ResponseFileData> responseFilesData, List <Assembly> allProjectIslands) { var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData)); var references = new List <string>(); var projectReferences = new List <Match>(); projectBuilder.Append(@" <ItemGroup>").Append(k_WindowsNewline); foreach (string file in assembly.sourceFiles) { if (!ShouldFileBePartOfSolution(file)) { continue; } var extension = Path.GetExtension(file).ToLower(); var fullFile = EscapedRelativePathFor(file); if (".dll" != extension) { projectBuilder.Append(" <Compile Include=\"").Append(fullFile).Append("\" />").Append(k_WindowsNewline); } else { references.Add(fullFile); } } projectBuilder.Append(@" </ItemGroup>").Append(k_WindowsNewline); var assemblyName = FileUtility.FileNameWithoutExtension(assembly.outputPath); projectBuilder.Append(@" <ItemGroup>").Append(k_WindowsNewline); // Append additional non-script files that should be included in project generation. if (allAssetsProjectParts.TryGetValue(assemblyName, out var additionalAssetsForProject)) { projectBuilder.Append(additionalAssetsForProject); } var islandRefs = references.Union(assembly.allReferences); foreach (string reference in islandRefs) { if (reference.EndsWith("/UnityEditor.dll", StringComparison.Ordinal) || reference.EndsWith("/UnityEngine.dll", StringComparison.Ordinal) || reference.EndsWith("\\UnityEditor.dll", StringComparison.Ordinal) || reference.EndsWith("\\UnityEngine.dll", StringComparison.Ordinal)) { continue; } var match = k_ScriptReferenceExpression.Match(reference); if (match.Success) { // assume csharp language // Add a reference to a project except if it's a reference to a script assembly // that we are not generating a project for. This will be the case for assemblies // coming from .assembly.json files in non-internalized packages. var dllName = match.Groups["dllname"].Value; if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName)) { projectReferences.Add(match); continue; } } string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference); AppendReference(fullReference, projectBuilder); } var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r)); foreach (var reference in responseRefs) { AppendReference(reference, projectBuilder); } projectBuilder.Append(@" </ItemGroup>").Append(k_WindowsNewline); if (0 < projectReferences.Count) { projectBuilder.Append(@" <ItemGroup>").Append(k_WindowsNewline); foreach (Match reference in projectReferences) { var referencedProject = reference.Groups["project"].Value; projectBuilder.Append(" <ProjectReference Include=\"").Append(referencedProject).Append(GetProjectExtension()).Append("\">").Append(k_WindowsNewline); projectBuilder.Append(" <Project>{").Append(ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll"))).Append("}</Project>").Append(k_WindowsNewline); projectBuilder.Append(" <Name>").Append(referencedProject).Append("</Name>").Append(k_WindowsNewline); projectBuilder.Append(" </ProjectReference>").Append(k_WindowsNewline); } projectBuilder.Append(@" </ItemGroup>").Append(k_WindowsNewline); } projectBuilder.Append(ProjectFooter()); return(projectBuilder.ToString()); }
private void UpdateLogFileList(string selectedDirectoryTitle = null) { if (selectedDirectoryTitle == null) { selectedDirectoryTitle = _selectedDirectoryTitle; } else { _selectedDirectoryTitle = selectedDirectoryTitle; } string errorSearchTerm; string warningSearchTerm; // remember user selection string selectedIndexValue = null; int selectedIndex = -1; selectedIndex = listBoxViewLogFiles.SelectedIndex; if (selectedIndex >= 0) { selectedIndexValue = listBoxViewLogFiles.SelectedItems[0].ToString(); } switch (selectedDirectoryTitle) { case "SnapRAID Scheduled Jobs": // SnapRAID Scheduled Jobs errorSearchTerm = _snapraidErrorSearchTerm; warningSearchTerm = _snapraidWarningSearchTerm; LexerToUse = LexerNameEnum.ScanRaid; _logSourcePath = $@"{Path.GetDirectoryName(Properties.Settings.Default.ConfigFileLocation)}\{Properties.Settings.Default.LogFileDirectory}\"; _logFileWatcher.Path = $@"{Path.GetDirectoryName(Properties.Settings.Default.ConfigFileLocation)}\{Properties.Settings.Default.LogFileDirectory}\"; _logFileWatcher.Filter = "*.log"; _logFileWatcher.EnableRaisingEvents = true; break; case "Elucidate": // Elucidate errorSearchTerm = _elucidateErrorSearchTerm; warningSearchTerm = _elucidateWarningSearchTerm; LexerToUse = LexerNameEnum.NLog; _logSourcePath = LogFileLocation.GetActiveLogFileLocation(); _logFileWatcher.Path = LogFileLocation.GetActiveLogFileLocation(); _logFileWatcher.Filter = "*.log"; _logFileWatcher.EnableRaisingEvents = true; break; default: _logFileWatcher.EnableRaisingEvents = false; return; } Log.Instance.Debug($"_logSourcePath : {_logSourcePath}"); listBoxViewLogFiles.Items.Clear(); if (!Directory.Exists(_logSourcePath)) { return; } DirectoryInfo logFileDirectoryInfo = new DirectoryInfo(_logSourcePath); List <FileInfo> allLogs = logFileDirectoryInfo.GetFiles("*.log").OrderByDescending(a => a.Name).ToList(); List <FileInfo> filteredLogs = new List <FileInfo>(); if (checkedFilesWithError.Checked) { IEnumerable <FileInfo> filesWithErrors = from file in allLogs let fileText = GetFileText(file.FullName) where fileText.Contains(errorSearchTerm) select file; filteredLogs = filteredLogs.Union(filesWithErrors).ToList(); } if (checkedFilesWithWarn.Checked) { IEnumerable <FileInfo> filesWithWarnings = from file in allLogs let fileText = GetFileText(file.FullName) where fileText.Contains(warningSearchTerm) select file; filteredLogs = filteredLogs.Union(filesWithWarnings).ToList(); } List <FileInfo> logsToShow = filteredLogs.Count > 0 ? filteredLogs : allLogs; logsToShow = logsToShow.OrderByDescending(a => a.Name).ToList(); foreach (FileInfo log in logsToShow) { listBoxViewLogFiles.Items.Add(log.Name); } // restore user selection, if it stil lexists if (selectedIndex >= 0 && !string.IsNullOrEmpty(selectedIndexValue)) { int indexFound = -1; indexFound = listBoxViewLogFiles.FindStringExact(selectedIndexValue); if (indexFound >= 0) { listBoxViewLogFiles.SelectedIndex = indexFound; } } }
public List <string> GetUniqueListOfCommands() { var allCommands = initCommands.Union(executeCommands).Union(deInitCommands); return(allCommands.Select(o => o.CommandName).Distinct().ToList());; }
public HttpResponseMessage Upload_Query_For_ElectronicFile(_For_ElectronicFile_Info info) { string result = string.Empty; try { List <Model.ElectronicFile> list = new List <Model.ElectronicFile>(); List <Model.ElectronicFile> listdata = new List <Model.ElectronicFile>(); using (Model.EntityContext db = new Model.EntityContext()) { list = (from x in db.ElectronicFile select x).ToList(); } if (!(info.fldUserID == "admin")) { list = (from x in list where x.fldUserID == info.fldUserID select x).ToList(); } DateTime BeginDate = DateTime.Parse(info.fldBeginDate); DateTime EndDate = DateTime.Parse(info.fldEndDate); list = (from x in list where x.fldTime >= BeginDate && x.fldTime <= EndDate select x).ToList(); if (!(info.obj == "" || info.obj == null)) { var query1 = from x in list where x.fldReport_Name.Contains(info.fldReport_Name) select x; var query2 = from x in list where x.fldReport_Type.Contains(info.fldReport_Type) select x; var query3 = from x in list where x.fldRName.Contains(info.fldRName) select x; listdata = query1.Union(query2).ToList(); listdata = listdata.Union(query3).ToList(); list = listdata; } list = list.OrderByDescending(x => x.fldTime).ToList(); result = rule.JsonStr("ok", "", list); } catch (Exception e) { result = rule.JsonStr("error", e.Message, ""); } return(new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") }); }
/// <summary> /// Divides the prescriptions into their own respective classifications. /// </summary> private void DividePrescriptions() { if (ScheduledPrescriptions == null) { ScheduledPrescriptions = new ObservableCollection <PrescriptionGroup>(); } if (AdministeredPrescriptions == null) { AdministeredPrescriptions = new ObservableCollection <PrescriptionGroup>(); } if (UnadministeredPrescriptions == null) { UnadministeredPrescriptions = new ObservableCollection <PrescriptionGroup>(); } if (SelectedPrescriptions == null) { SelectedPrescriptions = new ObservableCollection <PrescriptionGroup>(); } // past v. future for scheduled List <PrescriptionGroup> recentPast; try { recentPast = AllPrescriptions.Where(grp => (((grp.TimeStamp - DateTime.Now).TotalMinutes > -30) && ((grp.TimeStamp - DateTime.Now).TotalMinutes < 0))).ToList(); } catch (ArgumentNullException) { recentPast = new List <PrescriptionGroup>(); } List <PrescriptionGroup> future; try { future = AllPrescriptions.Where(grp => (grp.TimeStamp - DateTime.Now).TotalMinutes > 0).ToList(); } catch (ArgumentNullException) { future = new List <PrescriptionGroup>(); } var oc = recentPast.Union(future); ScheduledPrescriptions = new ObservableCollection <PrescriptionGroup>(oc); // selected var selected = AllPrescriptions.Where(grp => grp.IsSelectedOnly).ToList(); SelectedPrescriptions = new ObservableCollection <PrescriptionGroup>(selected); SelectedPrescriptions.CollectionChanged += SelectedPrescriptions_CollectionChanged; // administered v. unadministered try { foreach (PrescriptionGroup group in AllPrescriptions) { bool isAdministered = false; foreach (var med in group.Prescriptions) { if (med.AdministeredOn.HasValue) { isAdministered = true; break; } } if (isAdministered) { AdministeredPrescriptions.Add(group); } else { UnadministeredPrescriptions.Add(group); } } } catch (Exception) { } }
void ConfigureMac() { var classic_targets = new List <MacClassicTarget> (); var unified_targets = new List <MacUnifiedTarget> (); var hardcoded_unified_targets = new List <MacUnifiedTarget> (); RootDirectory = Path.GetFullPath(RootDirectory).TrimEnd('/'); if (AutoConf) { AutoConfigureMac(); } foreach (var proj in MacBclTests) { proj.Convert(this); } foreach (var proj in MacTestProjects.Where((v) => v.GenerateVariations)) { var file = Path.ChangeExtension(proj.Path, "csproj"); if (!File.Exists(file)) { throw new FileNotFoundException(file); } foreach (bool thirtyTwoBit in new bool[] { false, true }) { var unifiedMobile = new MacUnifiedTarget(true, thirtyTwoBit) { TemplateProjectPath = file, Harness = this, IsNUnitProject = proj.IsNUnitProject, }; unifiedMobile.Execute(); unified_targets.Add(unifiedMobile); if (!proj.SkipXMVariations) { var unifiedXM45 = new MacUnifiedTarget(false, thirtyTwoBit) { TemplateProjectPath = file, Harness = this, }; unifiedXM45.Execute(); unified_targets.Add(unifiedXM45); } } var classic = new MacClassicTarget() { TemplateProjectPath = file, Harness = this, }; classic.Execute(); classic_targets.Add(classic); } foreach (var proj in MacTestProjects.Where((v) => !v.GenerateVariations)) { var file = proj.Path; var unifiedMobile = new MacUnifiedTarget(true, false, true) { TemplateProjectPath = file, Harness = this, IsNUnitProject = proj.IsNUnitProject, }; unifiedMobile.Execute(); hardcoded_unified_targets.Add(unifiedMobile); } MakefileGenerator.CreateMacMakefile(this, classic_targets.Union <MacTarget> (unified_targets).Union(hardcoded_unified_targets)); }
private List <GameObject> IsRowBomb(Dot dot1, Dot dot2, Dot dot3) { List <GameObject> currentDots = new List <GameObject>(); if (dot1.isRowBomb) { currentMatches.Union(GetRowPieces(dot1.row)); } if (dot2.isRowBomb) { currentMatches.Union(GetRowPieces(dot2.row)); } if (dot3.isRowBomb) { currentMatches.Union(GetRowPieces(dot3.row)); } return(currentDots); }
public void ValidationRuleCompose(List <IValidationRule> validationRules) { _validationRules = _validationRules.Union(validationRules).ToList(); }
/// <summary> /// SetWebBrowserTable - for creating html mail /// </summary> public void SetWebBrowserTable() { List <ClientEventModel> clientEventModelsList = new List <ClientEventModel>(); allClientEventTrackWorkerIdList = new List <int>(); foreach (int clientEventId in _clientEventIdList) { ClientEventModel clientEvent = ClientEventDataAccess.LoadClientEvent(clientEventId); clientEvent.TrackWorkersId = ClientEvents_TrackWorkersDataAccess.LoadClientEventTrackWorkerIDList(clientEventId); allClientEventTrackWorkerIdList = allClientEventTrackWorkerIdList.Union(clientEvent.TrackWorkersId).ToList(); clientEventModelsList.Add(clientEvent); } stringBodyHTML += "<table style=\"border: 1px solid black;text-align:center;\">"; stringBodyHTML += "<tr>"; stringBodyHTML += "<td></td>"; foreach (ClientEventModel clientEvent in clientEventModelsList) { ClientModel client = ClientDataAccess.LoadClient(clientEvent.ClientID); stringBodyHTML += "<td style=\"border: 1px solid black;\">" + client.Name + "</td>"; } stringBodyHTML += "</tr>"; stringBodyHTML += "<tr>"; stringBodyHTML += "<td></td>"; foreach (ClientEventModel clientEvent in clientEventModelsList) { stringBodyHTML += "<td style=\"border: 1px solid black;\">" + clientEvent.Date + "</td>"; } stringBodyHTML += "</tr>"; stringBodyHTML += "<tr>"; stringBodyHTML += "<td style=\"border: 1px solid black;\"># Workers Needed</td>"; foreach (ClientEventModel clientEvent in clientEventModelsList) { stringBodyHTML += "<td style=\"border: 1px solid black;\">" + clientEvent.WorkersRequested + "</td>"; } stringBodyHTML += "</tr>"; stringBodyHTML += "<tr>"; stringBodyHTML += "<td style=\"border: 1px solid black;\">Track</td>"; foreach (ClientEventModel clientEvent in clientEventModelsList) { TrackModel track = TrackDataAccess.LoadTrack(clientEvent.TrackID); stringBodyHTML += "<td style=\"border: 1px solid black;\">" + track.Name + "</td>"; } stringBodyHTML += "</tr>"; stringBodyHTML += "<tr><td><b>Worker Name</b></td></tr>"; foreach (int trackWorkerId in allClientEventTrackWorkerIdList) { stringBodyHTML += "<tr>"; TrackWorkerModel trackWorker = TrackWorkerDataAccess.LoadTrackWorker(trackWorkerId); stringBodyHTML += "<td style=\"border: 1px solid black;\">" + trackWorker.FullName() + "</td>"; foreach (ClientEventModel clientEvent in clientEventModelsList) { if (clientEvent.TrackWorkersId.Contains(trackWorkerId)) { stringBodyHTML += "<td style=\"border: 1px solid black;\">X</td>"; } else { stringBodyHTML += "<td style=\"border: 1px solid black;\"> </td>"; } } stringBodyHTML += "</tr>"; } stringBodyHTML += "</table>"; //webBrowser.DocumentText += stringTableHTML; }
private void ConfigureMultiElementValues() { Mock <IFlowElement> element1 = new Mock <IFlowElement>(); element1.Setup(e => e.ElementDataKey).Returns("element1"); List <IElementPropertyMetaData> metaData1 = new List <IElementPropertyMetaData>() { new ElementPropertyMetaData(element1.Object, INT_PROPERTY, INT_PROPERTY_VALUE.GetType(), true), new ElementPropertyMetaData(element1.Object, NULL_STRING_PROPERTY, typeof(string), true), new ElementPropertyMetaData(element1.Object, LIST_PROPERTY, LIST_PROPERTY_VALUE.GetType(), true), new ElementPropertyMetaData(element1.Object, DUPLICATE_PROPERTY, typeof(string), true), }; element1.Setup(e => e.Properties).Returns(metaData1); Mock <IFlowElement> element2 = new Mock <IFlowElement>(); element2.Setup(e => e.ElementDataKey).Returns("element2"); List <IElementPropertyMetaData> metaData2 = new List <IElementPropertyMetaData>() { new ElementPropertyMetaData(element2.Object, STRING_PROPERTY, STRING_PROPERTY_VALUE.GetType(), true), new ElementPropertyMetaData(element2.Object, DUPLICATE_PROPERTY, typeof(string), true), }; element2.Setup(e => e.Properties).Returns(metaData2); DictionaryElementData elementData1 = new DictionaryElementData( new TestLogger <DictionaryElementData>(), _pipeline.Object); elementData1[INT_PROPERTY] = INT_PROPERTY_VALUE; elementData1[NULL_STRING_PROPERTY] = null; elementData1[LIST_PROPERTY] = LIST_PROPERTY_VALUE; DictionaryElementData elementData2 = new DictionaryElementData( new TestLogger <DictionaryElementData>(), _pipeline.Object); elementData2[STRING_PROPERTY] = STRING_PROPERTY_VALUE; List <IFlowElement> elements = new List <IFlowElement>() { element1.Object, element2.Object, }; _pipeline.Setup(p => p.FlowElements).Returns(elements); _pipeline.Setup(p => p.Process(It.IsAny <IFlowData>())) .Callback((IFlowData data) => { data.GetOrAdd("element1", (p) => elementData1); data.GetOrAdd("element2", (p) => elementData2); }); _pipeline.Setup(p => p.GetMetaDataForProperty(It.IsAny <string>())).Returns((string propertyName) => { var matches = metaData1.Union(metaData2) .Where(d => d.Name == propertyName); if (matches.Count() == 0 || matches.Count() > 1) { throw new PipelineDataException(""); } return(matches.Single()); }); }
private SqlScriptPublishModel BuildPublishModel() { SqlScriptPublishModel publishModel = new SqlScriptPublishModel(this.Parameters.ConnectionString); // See if any filtering criteria was specified. If not, we're scripting the entire database. Otherwise, the filtering // criteria should include the target objects to script. // bool hasObjectsSpecified = this.Parameters.ScriptingObjects != null && this.Parameters.ScriptingObjects.Any(); bool hasCriteriaSpecified = (this.Parameters.IncludeObjectCriteria != null && this.Parameters.IncludeObjectCriteria.Any()) || (this.Parameters.ExcludeObjectCriteria != null && this.Parameters.ExcludeObjectCriteria.Any()) || (this.Parameters.IncludeSchemas != null && this.Parameters.IncludeSchemas.Any()) || (this.Parameters.ExcludeSchemas != null && this.Parameters.ExcludeSchemas.Any()) || (this.Parameters.IncludeTypes != null && this.Parameters.IncludeTypes.Any()) || (this.Parameters.ExcludeTypes != null && this.Parameters.ExcludeTypes.Any()); bool scriptAllObjects = !hasObjectsSpecified && !hasCriteriaSpecified; // In the getter for SqlScriptPublishModel.AdvancedOptions, there is some strange logic which will // cause the SqlScriptPublishModel.AdvancedOptions to get reset and lose all values based the ordering // of when SqlScriptPublishModel.ScriptAllObjects is set. // publishModel.ScriptAllObjects = scriptAllObjects; if (scriptAllObjects) { // Due to the getter logic within publishModel.AdvancedOptions, we explicitly populate the options // after we determine what objects we are scripting. // PopulateAdvancedScriptOptions(this.Parameters.ScriptOptions, publishModel.AdvancedOptions); return(publishModel); } IEnumerable <ScriptingObject> selectedObjects = new List <ScriptingObject>(); if (hasCriteriaSpecified) { // This is an expensive remote call to load all objects from the database. // List <ScriptingObject> allObjects = publishModel.GetDatabaseObjects(); selectedObjects = ScriptingObjectMatcher.Match( this.Parameters.IncludeObjectCriteria, this.Parameters.ExcludeObjectCriteria, this.Parameters.IncludeSchemas, this.Parameters.ExcludeSchemas, this.Parameters.IncludeTypes, this.Parameters.ExcludeTypes, allObjects); } if (hasObjectsSpecified) { selectedObjects = selectedObjects.Union(this.Parameters.ScriptingObjects); } // Populating advanced options after we select our objects in question, otherwise we lose all // advanced options. After this call to PopulateAdvancedScriptOptions, DO NOT reference the // publishModel.AdvancedOptions getter as it will reset the options in the model. // PopulateAdvancedScriptOptions(this.Parameters.ScriptOptions, publishModel.AdvancedOptions); Logger.Write( LogLevel.Normal, string.Format( "Scripting object count {0}, objects: {1}", selectedObjects.Count(), string.Join(", ", selectedObjects))); string server = GetServerNameFromLiveInstance(this.Parameters.ConnectionString); string database = new SqlConnectionStringBuilder(this.Parameters.ConnectionString).InitialCatalog; foreach (ScriptingObject scriptingObject in selectedObjects) { publishModel.SelectedObjects.Add(scriptingObject.ToUrn(server, database)); } return(publishModel); }
public static void RegisterType(params Type[] types) { Types = Types.Union(types).ToList(); }
static void Main(string[] args) { var list1 = new List <StudentList>() { new StudentList { studentName = "jhon", Age = 20, standardId = 1, studentId = 1 }, new StudentList { studentName = "cena", Age = 22, standardId = 1, studentId = 2 }, new StudentList { studentName = "dawayne", Age = 21, studentId = 3, standardId = 2 }, new StudentList { studentName = "jhonson", Age = 19, standardId = 2, studentId = 4 }, new StudentList { studentName = "Rock", Age = 20, studentId = 5, standardId = 3 }, new StudentList { studentName = "Randy", Age = 19, standardId = 3, studentId = 6 }, new StudentList { studentName = "Orton", Age = 21, studentId = 7, standardId = 4 }, new StudentList { studentName = "Smith", Age = 19, standardId = 4, studentId = 8 } }; var list2 = new List <StudentList>() { new StudentList { studentName = "jhon", Age = 20, standardId = 1, studentId = 1 }, new StudentList { studentName = "cena", Age = 22, standardId = 1, studentId = 2 }, new StudentList { studentName = "dawayne", Age = 21, studentId = 3, standardId = 2 } }; var list3 = new List <StandadList>() { new StandadList { standardID = 1, standardName = "Standard-1" }, new StandadList { standardID = 2, standardName = "Standard-2" }, new StandadList { standardID = 3, standardName = "Standard-3" }, new StandadList { standardID = 4, standardName = "Standard-4" } }; //query1:joining by query union syntax var result1 = list1.Union(list2).ToList(); //printing query1 result foreach (var s in result1) { Console.WriteLine(s.studentName + " " + s.studentId); } //query2:joining by query join syntax var result2 = from s in list1 join st in list3 on s.standardId equals st.standardID select new { studentid = s.studentId, standardId = st.standardID, age = s.Age, studentName = s.studentName, standardName = st.standardName }; //printing qurey2 result Console.WriteLine("------------------------"); Console.WriteLine("----------query-2-------"); foreach (var s in result2) { Console.WriteLine("Id:" + s.studentid + " StandardName:" + s.standardName + " Name:" + s.studentName + " Age:" + s.age); } //query3:joining by query join syntax var result3 = from student in list1 group student by student.standardId; //printing qurey3 result Console.WriteLine("------------------------"); Console.WriteLine("----------query-3-------"); foreach (var s in result3) { Console.WriteLine("StandardId :" + s.Key); foreach (var a in s) { Console.WriteLine("Name:" + a.studentName); } Console.WriteLine("------------------------"); } }
protected void cbpnGiadinh_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e) { var cbpnGiadinh = sender as ASPxCallbackPanel; bool bChong = rbChong.Checked; List <FamilyRelationshipInfo> frListS1 = null; List <FamilyRelationshipInfo> frListS2 = null; List <FamilyRelationshipInfo> frListS3 = null; List <FamilyRelationshipInfo> frListS = null; List <FamilyRelationshipInfo> frListD1 = null; List <FamilyRelationshipInfo> frListD2 = null; List <FamilyRelationshipInfo> frListD3 = null; List <FamilyRelationshipInfo> frListD = null; int nhanvienDich = 0; int nhanvienNguon = 0; if (cbbSource.SelectedIndex != -1) { nhanvienNguon = Convert.ToInt32(cbbSource.SelectedItem.Value); frListS1 = frController.GetFamilyByEmployess(nhanvienNguon, 1); frListS2 = frController.GetFamilyByEmployess(nhanvienNguon, 2); frListS3 = frController.GetFamilyByEmployess(nhanvienNguon, 3); frListS = frListS1.Union(frListS2).Union(frListS3).ToList(); } if (cbbDest.SelectedIndex != -1) { nhanvienDich = Convert.ToInt32(cbbDest.SelectedItem.Value); frListD1 = frController.GetFamilyByEmployess(nhanvienDich, 1); frListD2 = frController.GetFamilyByEmployess(nhanvienDich, 2); frListD3 = frController.GetFamilyByEmployess(nhanvienDich, 3); frListD = frListD1.Union(frListD2).Union(frListD3).ToList(); } if (e.Parameter.StartsWith("TransferSelectedItem")) { if (frListD == null) { frListD = new List <FamilyRelationshipInfo>(); } var tempS = new List <FamilyRelationshipInfo>(); var tempD = new List <FamilyRelationshipInfo>(); string sourceItems = e.Parameter.Split(':')[1]; string destItems = e.Parameter.Split(':')[2]; string allItem = sourceItems + destItems; var tempList = frListS.ToList(); RemoveUnMap(tempList, frListD, bChong); foreach (string item in allItem.Split(',')) { if (string.IsNullOrEmpty(item)) { continue; } int rid = Convert.ToInt32(item); var ritem = tempList.Where(r => r.id == rid).FirstOrDefault(); if (ritem != null) { tempD.Add(ritem); } } for (int i = 0; i < tempD.Count; i++) { var ri = tempD[i]; int mrid = MapRelationshipId(ri.relationshipid, bChong); if (mrid == 0) { tempD.Remove(ri); } else { frListS.Remove(ri); ri.description = objRelation.GetRelationship(mrid).name; } } foreach (var ri in frListD) { ri.description = objRelation.GetRelationship(ri.relationshipid).name; } frListD = frListD.Union(tempD).ToList(); lbRelativeDest.DataSource = frListD; lbRelativeDest.DataBind(); foreach (var ri in frListS) { ri.description = objRelation.GetRelationship(ri.relationshipid).name; } lbRelativeSource.DataSource = frListS; lbRelativeSource.DataBind(); cbpnGiadinh.JSProperties["cpOP"] = 0; } else if (e.Parameter.StartsWith("RemoveSelectedItem")) { if (frListD == null) { frListD = new List <FamilyRelationshipInfo>(); } var tempS = new List <FamilyRelationshipInfo>(); var tempD = new List <FamilyRelationshipInfo>(); string sourceItems = e.Parameter.Split(':')[1]; string destRemoveItems = e.Parameter.Split(':')[2]; string destItems = e.Parameter.Split(':')[3]; string allItem = sourceItems + destItems; List <int> tempSrcIdList = new List <int>(); List <int> tempDestRemoveIdList = new List <int>(); List <int> tempDestAllIdList = new List <int>(); foreach (var strItem in sourceItems.Split(',')) { if (string.IsNullOrEmpty(strItem)) { continue; } int id = Convert.ToInt32(strItem); var item = frListS.Where(r => r.id == id).FirstOrDefault(); if (item != null) { tempSrcIdList.Add(id); } } foreach (var strItem in destRemoveItems.Split(',')) { if (string.IsNullOrEmpty(strItem)) { continue; } int id = Convert.ToInt32(strItem); var item = frListD.Where(r => r.id == id).FirstOrDefault(); if (item == null) { tempDestRemoveIdList.Add(id); } } foreach (var strItem in destItems.Split(',')) { if (string.IsNullOrEmpty(strItem)) { continue; } int id = Convert.ToInt32(strItem); var item = frListD.Where(r => r.id == id).FirstOrDefault(); if (item == null) { tempDestAllIdList.Add(id); } } tempSrcIdList = tempSrcIdList.Union(tempDestRemoveIdList).ToList(); tempDestAllIdList = tempDestAllIdList.Except(tempDestRemoveIdList).ToList(); foreach (var id in tempSrcIdList) { var ri = frController.GetFamilyRelationship(id); ri.description = objRelation.GetRelationship(ri.relationshipid).name; tempS.Add(ri); } foreach (var id in tempDestAllIdList) { var ri = frController.GetFamilyRelationship(id); int mrid = MapRelationshipId(ri.relationshipid, bChong); ri.description = objRelation.GetRelationship(mrid).name; tempD.Add(ri); } lbRelativeSource.DataSource = tempS; lbRelativeSource.DataBind(); foreach (var ri in frListD) { ri.description = objRelation.GetRelationship(ri.relationshipid).name; } frListD = frListD.Union(tempD).ToList(); lbRelativeDest.DataSource = frListD; lbRelativeDest.DataBind(); } else if (e.Parameter.StartsWith("LR")) { if (frListS != null) { foreach (var ri in frListS) { ri.description = objRelation.GetRelationship(ri.relationshipid).name; } lbRelativeSource.DataSource = frListS; lbRelativeSource.DataBind(); } if (frListD != null) { foreach (var ri in frListD) { ri.description = objRelation.GetRelationship(ri.relationshipid).name; } lbRelativeDest.DataSource = frListD; lbRelativeDest.DataBind(); } cbpnGiadinh.JSProperties["cpOP"] = 0; } else if (e.Parameter.StartsWith("Save")) { try { if (frListS == null) { return; } if (frListD == null) { frListD = new List <FamilyRelationshipInfo>(); } string destItems = e.Parameter.Split(':')[1]; var tempList = new List <FamilyRelationshipInfo>(); List <int> frDestIdList = new List <int>(); foreach (string stritem in destItems.Split(',')) { if (string.IsNullOrEmpty(stritem)) { continue; } int id = Convert.ToInt32(stritem); var item = frListD.Where(r => r.id == id).FirstOrDefault(); if (item == null) { frDestIdList.Add(id); } } foreach (var id in frDestIdList) { var item = frController.GetFamilyRelationship(id); int rid = MapRelationshipId(item.relationshipid, bChong); if (rid == 0) { continue; } item.relationshipid = rid; item.employeeid = nhanvienDich; frController.AddFamilyRelationship(item); } FamilyRelationshipInfo fri = new FamilyRelationshipInfo(); var emp = objEmployees.GetEmployees(nhanvienNguon); if (bChong) { //them thong tin chong fri.fullname = emp.fullname; fri.employeeid = nhanvienDich; fri.address = emp.placeofcurrent; fri.birthday = String.Format("{0:yyyy}", emp.birthday);; fri.occupation = emp.occupation; fri.placeofbirth = emp.placeofbirth; fri.relationshipid = 10; //10 = chong } else { //them thong tin vo fri.fullname = emp.fullname; fri.employeeid = nhanvienDich; fri.address = emp.placeofcurrent; fri.birthday = String.Format("{0:yyyy}", emp.birthday); fri.occupation = emp.occupation; fri.placeofbirth = emp.placeofbirth; fri.relationshipid = 11; //11 = vo } frController.AddFamilyRelationship(fri); cbpnGiadinh.JSProperties["cpOP"] = 1; } catch { cbpnGiadinh.JSProperties["cpOP"] = 2; } } }
private IEnumerator OnPlaced() { if (Vector3.Distance(this._multiPointsPositions[this._multiPointsPositions.Count - 1], this._multiPointsPositions[0]) >= this._closureSnappingDistance) { this._multiPointsPositions.Add(this._multiPointsPositions[0]); this.RefreshCurrentFloor(); } base.enabled = false; this._wasPlaced = true; yield return(null); if (!this._craftStructure) { this._craftStructure = base.GetComponentInChildren <Craft_Structure>(); } UnityEngine.Object.Destroy(base.GetComponent <Collider>()); UnityEngine.Object.Destroy(base.GetComponent <Rigidbody>()); this._craftStructure.GetComponent <Collider>().enabled = false; if (Scene.HudGui) { Scene.HudGui.RoofConstructionIcons.Shutdown(); } if (this._craftStructure) { Transform ghostRoot = this._raftRoot; Transform transform = ghostRoot; transform.name += "Ghost"; Transform logGhostPrefab = this._logPrefab; this._logPrefab = Prefabs.Instance.LogFloorBuiltPrefab; this._logPool = new Stack <Transform>(); this._newPool = new Stack <Transform>(); this._raftRoot = new GameObject("RaftRootBuilt").transform; this._raftRoot.position = this._multiPointsPositions[0]; this.SpawnFloor(); Craft_Structure.BuildIngredients ri = this._craftStructure._requiredIngredients.FirstOrDefault((Craft_Structure.BuildIngredients i) => i._itemID == this.$this._logItemId); List <GameObject> logStacks = new List <GameObject>(); IEnumerator enumerator = this._raftRoot.GetEnumerator(); try { while (enumerator.MoveNext()) { object obj = enumerator.Current; Transform transform2 = (Transform)obj; transform2.gameObject.SetActive(false); logStacks.Add(transform2.gameObject); } } finally { IDisposable disposable; if ((disposable = (enumerator as IDisposable)) != null) { disposable.Dispose(); } } if (ri._renderers != null) { ri._renderers = logStacks.Union(ri._renderers).ToArray <GameObject>(); } else { ri._renderers = logStacks.ToArray(); } ri._amount += this._raftRoot.childCount; this._logPrefab = logGhostPrefab; this._raftRoot.transform.parent = base.transform; ghostRoot.transform.parent = base.transform; this._craftStructure.GetComponent <Collider>().enabled = true; BoxCollider bc; if (this._craftStructure.GetComponent <Collider>() is BoxCollider) { bc = (BoxCollider)this._craftStructure.GetComponent <Collider>(); } else { bc = this._craftStructure.gameObject.AddComponent <BoxCollider>(); bc.isTrigger = true; } Bounds b = new Bounds(base.transform.position, Vector3.zero); for (int j = 1; j < this._multiPointsPositions.Count; j++) { b.Encapsulate(this._multiPointsPositions[j]); } Vector3 bottom = base.transform.position; bottom.y -= 5f; b.Encapsulate(bottom); bc.center = base.transform.InverseTransformPoint(b.center); Vector3 finalColliderSize = base.transform.InverseTransformVector(b.size); float alpha = 0f; while (alpha < 1f) { bc.size = Vector3.Lerp(Vector3.zero, finalColliderSize, alpha += Time.deltaTime * 5f); yield return(null); } bc.size = finalColliderSize; yield return(null); this._craftStructure.manualLoading = true; while (LevelSerializer.IsDeserializing && !this._craftStructure.WasLoaded) { yield return(null); } this._craftStructure.Initialize(); this._craftStructure.gameObject.SetActive(true); base.GetComponent <Renderer>().enabled = false; yield return(null); if (bc != null) { bc.enabled = false; bc.enabled = true; } this._logPool = null; this._newPool = null; this._rowPointsBuffer = null; } yield break; }
void updateStun() { //Attribute stuns foreach (string busterID in BusterIDs) { Entity buster = Entities[busterID]; EntityState es = buster.Positions[Round]; int previousRound = Round - 1; if (es.State == StateStunned && es.Value == LimBusterStunDuration) { es = buster.Positions[previousRound]; int enemyTeamID = 1 - TeamID; List <Entity> staticEnemyBusters = Entities.Where(e => e.Value.Type == enemyTeamID) .Where(e => e.Value.Positions.ContainsKey(Round)) .Where(e => e.Value.Positions.ContainsKey(previousRound)) .Where(e => e.Value.Positions[Round].X == e.Value.Positions[previousRound].X) .Where(e => e.Value.Positions[previousRound].State != StateStunned) .Where(e => Distance(es.X, es.Y, e.Value.Positions[Round].X, e.Value.Positions[Round].Y) <= LimStunMax) .Select(e => e.Value).ToList(); if (staticEnemyBusters.Count() == 1) { string bid = "" + staticEnemyBusters[0].Type + "," + staticEnemyBusters[0].ID; addStun(bid, busterID); } else { Console.Error.WriteLine("Cannot attribute stunned " + busterID + " to buster"); } } } //Update timers foreach (string busterID in BusterIDs.Union(EnemyBusterIDs).ToList()) { //Opening if (!Entities.ContainsKey(busterID)) { Dashboards[Round].StunTimers[busterID] = 0; continue; } //For a stunned buster, the countdown is the duration int stunnedCountdown = 0; if (Round > 0) { stunnedCountdown = Math.Max(0, Dashboards[Round - 1].StunTimers[busterID] - 1); } if (Entities[busterID].Positions.ContainsKey(Round)) { EntityState es = Entities[busterID].Positions[Round]; if (es.State == 2) { stunnedCountdown = es.Value; } } //For a non stunned buster, the countdown is the previous stun event int stunTimer = 0; if (StunEvents.Exists(s => s.BusterID == busterID)) { int latestRound = StunEvents.Where(s => s.BusterID == busterID).OrderByDescending(s => s.Round).First().Round; int difference = LimBusterStunTimer - (Round - latestRound); stunTimer = Math.Max(0, difference); } // Dashboards[Round].StunTimers[busterID] = Math.Max(stunTimer, stunnedCountdown); } }
/** * @params showAll, show all other people's checkRecord * @params showDeputy, only show if user is other people's deputy * @params showSupervisor, only show if user is other people's supervisor * @params range, only shows records after today - spacific days */ public async Task <List <NotificationModel> > GetNotificationAsync(string id, bool showAll = false, bool showDeputy = false, bool showSupervisor = false, int range = -7) { using (var dbContext = new AppDbContext(builder.Options)) { DateTime dateBound = DateTime.Today.AddDays(range); if (showAll) { return(await(from record in dbContext.CheckRecord join user in dbContext.UserInfo on record.UserId equals user.Id where record.CheckedDate > dateBound && (!string.IsNullOrWhiteSpace(record.OffType) || !string.IsNullOrWhiteSpace(record.OvertimeEndTime)) select new NotificationModel { Id = record.Id, UserName = user.UserName, CheckedDate = record.CheckedDate.ToString("yyyy-MM-dd"), OffType = record.OffType, OffTime = $"{record.OffTimeStart} - {record.OffTimeEnd}", OffReason = record.OffReason, StatusOfApproval = record.StatusOfApproval, OvertimeEndTime = record.OvertimeEndTime, StatusOfApprovalForOvertime = record.StatusOfApprovalForOvertime }).ToListAsync()); } List <NameListModel> userDeputy = new List <NameListModel>(), userSupervisor = new List <NameListModel>(); if (showDeputy) { userDeputy = await(from deputy in dbContext.UserDeputy join user in dbContext.UserInfo on deputy.UserId equals user.Id where deputy.DeputyId == id select new NameListModel { Label = user.UserName, Value = user.Id }).ToListAsync(); } if (showSupervisor) { userSupervisor = await(from supervisor in dbContext.UserSupervisor join user in dbContext.UserInfo on supervisor.UserId equals user.Id where supervisor.SupervisorId == id select new NameListModel { Label = user.UserName, Value = user.Id }).ToListAsync(); } var ulist = userDeputy.Union(userSupervisor).ToList(); var result = await dbContext.CheckRecord .Where(s => ulist.Any(w => w.Value == s.UserId) && s.CheckedDate > dateBound && (!string.IsNullOrWhiteSpace(s.OffType) || !string.IsNullOrWhiteSpace(s.OvertimeEndTime))) .Select(s => new NotificationModel { Id = s.Id, UserName = ulist.FirstOrDefault(z => z.Value == s.UserId).Label, CheckedDate = s.CheckedDate.ToString("yyyy-MM-dd"), OffType = s.OffType, OffTime = $"{s.OffTimeStart.ToString()} - {s.OffTimeEnd.ToString()}", OffReason = s.OffReason, OvertimeEndTime = s.OvertimeEndTime, StatusOfApproval = s.StatusOfApproval, StatusOfApprovalForOvertime = s.StatusOfApprovalForOvertime }) .ToListAsync(); return(result); } }
public HttpResponseMessage Upload_Query(Upload_Query_Info info) { string result = string.Empty; try { List <Model.tblReportArchive> list = new List <Model.tblReportArchive>(); List <Model.tblReportArchive> listdata = new List <Model.tblReportArchive>(); using (Model.EntityContext db = new Model.EntityContext()) { list = (from x in db.tblReportArchive select x).ToList(); } if (!(info.fldUserID == "admin")) { list = (from x in list where x.fldUserID == info.fldUserID select x).ToList(); } if (!(info.obj == "" || info.obj == null)) { var query1 = from x in list where x.fldReport_Name.Contains(info.obj) select x; var query2 = from x in list where x.fldReport_Type.Contains(info.obj) select x; var query3 = from x in list where x.fldRName.Contains(info.obj) select x; var query4 = from x in list where x.fldTime.Contains(info.obj) select x; listdata = query1.Union(query2).ToList(); listdata = listdata.Union(query3).ToList(); listdata = listdata.Union(query4).ToList(); list = listdata; } result = rule.JsonStr("ok", "", list); } catch (Exception e) { result = rule.JsonStr("error", e.Message, ""); } return(new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") }); }
public Dictionary <Key, List <Fraction> > Calculate(int p, int k) { if (p < 0 || p > 2) { throw new ArgumentException($"p must be 0, 1 or 2"); } // coefficients of powers of e for the beta term var betaList = new List <BetaBase> { new Beta0(), new Beta1(), new Beta2(), new Beta3(), }; var besselList = new List <BesselBase> { new Bessel0(k), new Bessel1(k), new Bessel2(k), new Bessel3(k), }; Func <int, int, int> besselOrderFuncPosExp = (b, d) => { return(k - l + 2 * p - b + d); }; Func <int, int, int> besselOrderFuncNegExp = (b, d) => { return(k + l - 2 * p + b - d); }; var bUpper = -(4 - 2 * p); // binom upper coeff var dUpper = -2 * p; // binom upper coeff var bMax = bUpper == 0 ? 0 : 3; var dMax = dUpper == 0 ? 0 : 3; var resultsPos = new List <Result>(); var resultsNeg = new List <Result>(); for (int b = 0; b <= bMax; b++) { for (int d = 0; d <= dMax; d++) { if ((b + d) < 4) { var resultPos = CalculateCoefficient(b, d, besselOrderFuncPosExp, bUpper, dUpper, betaList, besselList); resultsPos.Add(resultPos); var resultNeg = CalculateCoefficient(b, d, besselOrderFuncNegExp, bUpper, dUpper, betaList, besselList); resultsNeg.Add(resultNeg); } } } var answer = $"k={k}, 1st:{WriteOutput(resultsPos)} , 2nd:{WriteOutput(resultsNeg)}"; Debug.Write(answer); var allResults = resultsPos.Union(resultsNeg).ToList(); var k1Series = GetFinalSeries(resultsPos); var k2Series = GetFinalSeries(resultsNeg); var sumSeries = GetFinalSeries(allResults); var dictResults = new Dictionary <Key, List <Fraction> > { { Key.k1, k1Series }, { Key.k2, k2Series }, { Key.Sum, sumSeries } }; return(dictResults); }
private void button3_Click(object sender, EventArgs e) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); richTextBox1.Clear(); List <string> text1 = new List <string>(); List <string> text2 = new List <string>(); List <string> listNGram1 = new List <string>(); List <string> listNGram2 = new List <string>(); List <Matrix> matrix1 = new List <Matrix>(); List <Matrix> matrix2 = new List <Matrix>(); int nGramSize = Convert.ToInt32(textBox2.Text); if (nGramSize == 0) { MessageBox.Show("NGram size is must be set greater than 0."); } string path1 = textBox1.Text; string path2 = textBox3.Text; if ((textBox1.Text != null) && (textBox2.Text != null) && (textBox3.Text != null)) { /* Extracting text from .docx, .doc, .pdf. .txt. .ppt, .pptx file*/ text1 = textExtracting(path1); text2 = textExtracting(path2); /*Creating Tri-grams of those text after filtering stopwords, delimiters etc.*/ listNGram1 = createNGramText(text1, nGramSize); listNGram2 = createNGramText(text2, nGramSize); /*Creating distance matrices i.e. Matrix1 and Matrix2 in Oracle 10g Database*/ matrix1 = createMatrix(listNGram1); matrix2 = createMatrix(listNGram2); /*Find total matched values from distance matrices*/ var matched = from outer in matrix1 from inner in matrix2 where outer.Row.Equals(inner.Row) && outer.Column.Equals(inner.Column) && outer.Value.Equals(inner.Value) select new { outer, inner }; /*Find total non-matched values from distance matrices*/ var nonMatchedItems = matrix1.Where(l1 => !matrix2.Any(l2 => (l1.Row == l2.Row) && (l1.Column == l2.Column) && (l1.Value == l2.Value))).Concat(matrix2.Where(l1 => !matrix1.Any(l2 => (l1.Row == l2.Row) && (l1.Column == l2.Column) && (l1.Value == l2.Value)))); /*Find out total intersect, union and minus values between two distance matrics*/ var matrixIntersect = matrix1.Intersect(matrix2, new MatrixComparer()); richTextBox1.AppendText("\nIntersect Value: " + matrixIntersect.Count() + "\n"); var matrixUnion = matrix1.Union(matrix2, new MatrixComparer()); richTextBox1.AppendText("Union Value: " + matrixUnion.Count() + "\n"); var matrixMinus = matrixUnion.Except(matrixIntersect, new MatrixComparer()); richTextBox1.AppendText("The total number of elements in Matrix1: " + matrix1.Count + "\n"); richTextBox1.AppendText("The total number of elements in Matrix2: " + matrix2.Count + "\n"); /*Finally Calulating the Co-Occarances between Matrix1 and Matrix2 databases to find out the measure of similarity*/ float matrixJaccardCoefficient = (float)matrixIntersect.Count() / (float)(matrix1.Count + matrix2.Count - matrixIntersect.Count()); float matrixJaccardDistance = (float)(matrixUnion.Count() - matrixIntersect.Count()) / (float)matrixUnion.Count(); float matrixDiceCoefficient = (float)(2 * matrixIntersect.Count()) / (float)(matrix1.Count + matrix2.Count); float matrixDiceDissimilarity = (float)1 - ((float)(2 * matrixIntersect.Count()) / (float)(matrix1.Count + matrix2.Count)); float matrixOverlapCoefficient = (float)matrixIntersect.Count() / (float)Math.Min(matrix1.Count, matrix2.Count); float matrixCosineSimilarityMeasure = (float)matrixIntersect.Count() / (float)(Math.Sqrt(matrix1.Count) * Math.Sqrt(matrix2.Count)); float matrixSimpleMatchingCoefficient = (float)matrixIntersect.Count() / (float)matrixUnion.Count(); richTextBox1.AppendText("\nJaccard Coefficient (Similarity): " + matrixJaccardCoefficient + "\n"); richTextBox1.AppendText("Jaccard Coefficient (Dis-similarity): " + matrixJaccardDistance + "\n"); richTextBox1.AppendText("Dice Similarity Coefficient: " + matrixDiceCoefficient + "\n"); richTextBox1.AppendText("Dice Dissimilarity Coefficient: " + matrixDiceDissimilarity + "\n"); richTextBox1.AppendText("Overlap Coefficient: " + matrixOverlapCoefficient + "\n"); richTextBox1.AppendText("Cosine Similarity Measure: " + matrixCosineSimilarityMeasure + "\n"); richTextBox1.AppendText("Simple Matching Coefficient: " + matrixSimpleMatchingCoefficient + "\n"); textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); stopwatch.Stop(); richTextBox1.AppendText("Time elapsed: " + stopwatch.Elapsed); } else { MessageBox.Show("Sorry there is no file!!!"); } }
public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Pret pret = db.prets.Find(id); if (pret == null) { return(HttpNotFound()); } pret.emprunteur = db.adherents.Find(pret.AdherentID); pret.leLivrePrete = db.livres.Find(pret.LivreID); var livresPretes = from l in db.prets select l.leLivrePrete; var livreNonPretes = from l in db.livres where !livresPretes.Contains(l) select l; var adherentAutorisable = from a in db.adherents where a.pretsEnCours.Count == 3 select a; List <Adherent> adherentAutorise = adherentAutorisable.ToList <Adherent>(); List <Adherent> adhWithDepas = new List <Adherent>(); var listpret = from p in db.prets select p; List <Pret> listprets = listpret.ToList <Pret>(); var listAdherents = from a in db.adherents select a; List <Adherent> listAdherent = listAdherents.ToList <Adherent>(); foreach (Pret pr in listprets) { Adherent d = db.adherents.Find(pr.AdherentID); if (DateTime.Compare(pr.getDateRetour().Date, DateTime.Now.Date) < 0) { adhWithDepas.Add(d); listAdherent.Remove(d); } } foreach (Adherent d in adherentAutorise) { listAdherent.Remove(d); } var list = adhWithDepas.GroupBy(x => x.ID).Select(y => y.First()); List <Adherent> lista = list.ToList <Adherent>(); lista.Union(adherentAutorise); if (livreNonPretes.Count() == 0 || listAdherent.Count() == 0) { var adherentAutorisee = from a in db.adherents where a.ID == pret.AdherentID select a;; livreNonPretes = from l in db.livres where l.ID == pret.LivreID select l; ViewBag.AdherentID = new SelectList(adherentAutorisee, "ID", "nom", pret.AdherentID); } else { ViewBag.AdherentID = new SelectList(listAdherent, "ID", "nom", pret.AdherentID); } ViewBag.LivreID = new SelectList(livreNonPretes, "ID", "titre", pret.LivreID); return(View(pret)); }