/// <summary> /// Initialises a new instance of the <see cref="TableInfo"/> class. /// </summary> /// <param name="columns">The columns that are mapped for the table.</param> /// <param name="identifierStrategy">The identifier strategy used by the table.</param> /// <param name="name">The name of the table.</param> /// <param name="schema">The database schema the table exists within (e.g. 'dbo'); otherwise null.</param> /// <exception cref="ArgumentNullException">Thrown if columns or name are null.</exception> /// <exception cref="MappingException">Thrown if no there is a problem with the column mappings.</exception> public TableInfo( IList<ColumnInfo> columns, IdentifierStrategy identifierStrategy, string name, string schema) { if (columns == null) { throw new ArgumentNullException("columns"); } if (name == null) { throw new ArgumentNullException("name"); } this.columns = new ReadOnlyCollection<ColumnInfo>(columns); this.identifierStrategy = identifierStrategy; this.name = name; this.schema = schema; this.identifierColumn = columns.FirstOrDefault(c => c.IsIdentifier); this.insertColumnCount = columns.Count(c => c.AllowInsert); this.updateColumnCount = columns.Count(c => c.AllowUpdate); this.ValidateColumns(); }
private int[,] BuildMatrix(IList<Drop> goblet, int blocksCount, int chunkSize) { var rowsCount = goblet.Count() * chunkSize; var columnsCount = (blocksCount * chunkSize) + 1; var matrix = new int[rowsCount, columnsCount]; for (int dropIdx = 0; dropIdx < goblet.Count(); dropIdx++) { var drop = goblet[dropIdx]; for (int i = 0; i < chunkSize; i++) { var row = (dropIdx * chunkSize) + i; matrix[row, columnsCount - 1] = drop.Data[i]; foreach (var part in drop.SelectedParts) { var col = (part * chunkSize) + i; matrix[row, col] = 1; } } } return matrix; }
/// <summary> /// Convert numbers to spark chart strings. /// </summary> /// <param name="data">List or Array of numbers</param> /// <returns>empty string if <paramref name="data"/>is <code>null</code> or empty.</returns> public static String Render(IList<double> data) { var ticks = TickProvider.Ticks; if (data == null || data.Count == 0) return string.Empty; char[] res = new char[data.Count()]; double min = data.Min(); double max = data.Max(); double step = (max - min) / (ticks.Length - 1); if (step.Equals(0d)) step = 1; for (var i = 0; i < data.Count(); i++) { var val = data[i]; double d = (val - min)/step; // if it's 10^-10 close to its rounded, round; floor otherwise int tick = (int) ((Math.Abs(Math.Round(d) - d) < 1e-10) ? Math.Round(d) : Math.Floor((val - min) / step)); res[i] = ticks[tick]; } return new string(res); }
private int SolveFive(BombSettings settings, IList<Color> colors) { if (settings.SerialLastDigit == Parity.NotSet) { throw new NeedSerialLastDigitException(); } // If the last wire is black and the last digit of the serial number is odd, cut the fourth wire. else if (colors.Last() == Color.Black && settings.SerialLastDigit == Parity.Odd) { return 4; } // Otherwise, if there is exactly one red wire and there is more than one yellow wire, cut the first wire. else if (colors.Count(c => c == Color.Red) == 1 && colors.Count(c => c == Color.Yellow) > 1) { return 1; } // Otherwise, if there are no black wires, cut the second wire. else if (colors.Count(c => c == Color.Black) == 0) { return 2; } // Otherwise, cut the first wire. else { return 1; } }
/// <summary> /// The cross product of two double vectors, A and B, which are of length, 2. /// In actuality, there is no cross-product for 2D. This is shorthand for 2D systems /// that are really simplifications of 3D. The returned scalar is actually the value in /// the third (read: z) direction. /// </summary> /// <param name = "A">1D double Array, A</param> /// <param name = "B">1D double Array, B</param> /// <returns></returns> public static double crossProduct2(IList<double> A, IList<double> B) { if (((A.Count() == 2) && (B.Count() == 2)) || ((A.Count() == 3) && (B.Count() == 3) && A[2] == 0.0 && B[2] == 0.0)) return A[0] * B[1] - B[0] * A[1]; throw new Exception("This cross product \"shortcut\" is only used with 2D vectors to get the single value in the," + "would be, Z-direction."); }
public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand) { int num; if (paramList.Count() == 1) { // display random quote Connection.GetData(Data.UrlQuote, "get", jObject => { if ((bool)jObject["success"]) { Utils.SendChannel((string)jObject["result"].SelectToken("id") + ": " + (string)jObject["result"].SelectToken("quote")); } else { Utils.SendChannel("No quotes found."); } }, Utils.HandleException); } else if (paramList[1] == "add") { if (isIngameCommand == false) { var quote = ""; for (var l = 2; l < paramList.Count(); l++) { quote = quote + paramList[l] + " "; } Connection.GetData(string.Format(Data.UrlQuoteAdd, user.Nick, user.Hostmask, quote.Trim()), "get", jObject => Utils.SendChannel(string.Format("Quote #{0} has been added.", jObject["result"].SelectToken("id"))), Utils.HandleException); } else { Utils.SendChannel("This command is restricted to the IRC channel only."); } } else if (int.TryParse(paramList[1], out num)) { Connection.GetData(string.Format(Data.UrlQuoteSpecific, num), "get", jObject => { if ((bool)jObject["success"]) { Utils.SendChannel((string)jObject["result"].SelectToken("quote")); } else { Utils.SendChannel("Specific quote not found."); } }, Utils.HandleException); } else { Utils.SendChannel("Usage: !quote add <message>"); } }
public virtual void PrintReportFooter(StreamWriter streamWriter, IList<AllItem> allItems) { int drCount = allItems.Count(ai => ai.Classification == "Dr"); int crCount = allItems.Count(ai => ai.Classification == "Cr"); decimal drAmount = allItems.Where(ai => ai.Classification == "Dr").Sum(ai => ai.Amount); decimal crAmount = allItems.Where(ai => ai.Classification == "Cr").Sum(ai => ai.Amount); streamWriter.WriteLine(string.Format(this.reportFooterFormat, drCount, drAmount, crCount, crAmount)); }
public static DailyBuildSummary Create(DateTime date, IList<BuildDetails> dailyBuilds) { return new DailyBuildSummary() { Date = date, FailedBuilds = dailyBuilds.Count(b => b.Status == BuildState.Broken), TotalBuilds = dailyBuilds.Count(), NumberChangedFiles = dailyBuilds.Sum(b => b.NumberChangedFiles) }; }
public IList<CurveSegment> GenerateCurveSegments(IList<DataPoint> dataPoints) { var numDataPoints = dataPoints.Count(); if (numDataPoints < 3) throw new ArgumentException("Not enough data points"); var lastKnownSlope = 0.0; var lastKnownSlopeMagnitude = 0.0; var listOfCurveSegments = new List<CurveSegment>(); var listOfCurrentPoints = new List<DataPoint>(); listOfCurrentPoints.Add(dataPoints.First()); for (var i = 1; i < dataPoints.Count(); i++) { var lastDataPoint = dataPoints[i - 1]; var currentDataPoint = dataPoints[i]; var discoveredSlope = currentDataPoint.YCoordinate - currentDataPoint.YCoordinate; var discoveredSlopeMagnitude = Math.Abs(discoveredSlope); /* * Test discovered slope value. There's only three possibilities: * 1. The discovered slope is "zero", which means it's still a part of the current segment * 2. The discovered slope is positive * 3. The discovered slope is negative * * Compare with the previous slope, which can be: * 1. Positive * 2. Negative * 3. "Zero" */ /* * If the last known slope is zero or if the previous slope was negative and the current slope is positive * or if the previous slope was positive and the current slope is negative, seal the current segment and * create a new one */ if ((lastKnownSlopeMagnitude < Limits.MaxPrecision && discoveredSlopeMagnitude > Limits.MaxPrecision) || (lastKnownSlope < 0 && discoveredSlope > 0) || (lastKnownSlope > 0 && discoveredSlope < 0)) { listOfCurveSegments.Add(new CurveSegment(listOfCurrentPoints)); listOfCurrentPoints = new List<DataPoint>(); } //The slopes are the same polarity listOfCurrentPoints.Add(currentDataPoint); lastKnownSlope = discoveredSlope; lastKnownSlopeMagnitude = discoveredSlopeMagnitude; } return listOfCurveSegments; }
public static double Length(IList<IGeoLocation> cities) { var length = 0d; for (var i = 0; i < cities.Count() - 1; i++) { length = length + Distance(cities[i], cities[i + 1]); } length = length + Distance(cities[cities.Count() - 1], cities[0]); return length; }
private static int GetResult(IList<Tree> list) { var total = 0; for (var i = 0; i < list.Count(); i++) { total += list[i].Age; } return total/list.Count(); }
public void should_parse_objects_symbols_and_properties_when_parsing_more_complex_xml_content() { Lexemes = Parser.Parse(ComplexXml); Lexemes.Count.ShouldBe(136); Lexemes.Count(lx => lx.Type == LexemType.Comment).ShouldBe(6); }
private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length) { IList<ulong> sequence = new List<ulong>(); int count = seedSequence.Count(); if (length <= count) { sequence = seedSequence.Take((int)length).ToList(); } else { sequence = seedSequence; for (int i = count; i < length; i++) { ulong num = 0; for (int j = 0; j < count; j++) { num += sequence[sequence.Count - 1 - j]; } sequence.Add(num); } } return sequence; }
public static string FindPositionPart(IList<string> parts, int cursorPosition, out int foundPartsIndex, out int cursorInPartPosition) { cursorInPartPosition = 0; var partsComplete = parts.Aggregate(String.Empty, (aggr, s) => aggr + s); for (int i = 0; i < parts.Count(); i++) { var partsLower = parts.Take(i).Aggregate(String.Empty, (aggr, s) => aggr + s); var partsUpper = parts.Take(i + 1).Aggregate(String.Empty, (aggr, s) => aggr + s); var b = partsLower.Length; var t = partsUpper.Length; if ((cursorPosition >= b && cursorPosition < t) || partsUpper == partsComplete) { if (parts[i] == WorkDayParser.itemSeparator.ToString() || parts[i] == WorkDayParser.hourProjectInfoSeparator.ToString()) { // cursor left of separator foundPartsIndex = i - 1; var prevPart = parts.ElementAt(foundPartsIndex); // find out where in the found part the cursor is, need to use prevpart an its length cursorInPartPosition = prevPart.Length; return prevPart; } else { // find out where in the found part the cursor is cursorInPartPosition = cursorPosition - b; foundPartsIndex = i; return parts.ElementAt(i); } } } // not found foundPartsIndex = -1; return String.Empty; }
// Arg(ControllerName),Param(..),.. -> Arg(ControllerName),Arg('Index'),... public static IList<Token> Rewrite(IList<Token> tokens) { //"--command" if (tokens.Count() >= 2 && tokens[0].TokenType==TokenType.Argument && tokens[0].Value.EqualsIC("help") && tokens[1].TokenType==TokenType.Argument) { tokens[1] = new Token(tokens[1].Value,TokenType.ParameterValue,tokens[1].Index); tokens.Insert(1,new Token("command",TokenType.Parameter,1)); //index:2 if (tokens.Count() >= 4) { tokens[3] = new Token(tokens[3].Value, TokenType.ParameterValue, tokens[1].Index); } tokens.Insert(3, new Token("action", TokenType.Parameter, 2)); } //help maps to index (should have routing here) if (tokens.Count() == 0) { tokens.Add(new Token("help",TokenType.Argument,0)); } //Index rewrite: var indexToken= new Token("Index", TokenType.Argument,1); if (tokens.Count()>=2 && tokens[1].TokenType!=TokenType.Argument && tokens[0].TokenType==TokenType.Argument) { tokens.Insert(1,indexToken); } else if (tokens.Count()==1 && tokens[0].TokenType==TokenType.Argument) { tokens.Add(indexToken); } return tokens; }
public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand) { if (Utils.IsOp(user.Nick)) { if (paramList.Count() == 1) { Utils.SendNotice("Usage: !mcb <name> <optional:number>", user.Nick); } else { Connection.GetPlayerLookup(paramList[1], bans => { if (bans.Local != null && bans.Local.Any()) { var limit = 1; int i; if (paramList.Count() == 3 && Int32.TryParse(paramList[2], out i)) { // a count is given limit = int.Parse(paramList[2]); } for (var j = 0; j < limit; j++) { var localBan = bans.Local[j].Replace("\r\n", "") .Replace("\r", "") .Replace("\n", "") .Replace("\0", "") .Split(' '); var banReason = ""; for (var k = 4; k < localBan.Count(); k++) { banReason += localBan[k] + " "; } Utils.SendNotice( string.Concat("Server: ", localBan[2], ", Reason: ", Utils.Truncate(banReason.Trim(), 25), " URL: ", "http://www.mcbans.com/ban/" + localBan[1]), user.Nick); } } else { Utils.SendNotice("This player does not have any local bans.", user.Nick); } }, Utils.HandleException); } } else { Utils.SendChannel(Data.MessageRestricted); } }
public override ISet<CreatureCard> ChooseAttackers(IList<CreatureCard> possibleAttackers) { if (possibleAttackers.Count() == 0) return null; var chosenSet = new HashSet<CreatureCard>(); PrintPossibleAttackers(possibleAttackers); Console.WriteLine (); while(true) { Console.Write("mla> "); string input = Console.In.ReadLine().Trim(); // if user simply presses enter or white space, repeat list of possible attackers and chosen attackers if(String.IsNullOrEmpty(input)) { PrintPossibleAttackers(possibleAttackers); PrintChosenCreatures(chosenSet); continue; } // attempt to parse as a number. If is a number in range, add to set int chosen; if(Int32.TryParse(input,out chosen)) { if(chosen == -1) break; // if the chosen number is in range, add it to the set // if not in the set already, or remove it if it is in the set. // otherwise, tsk-tsk the user if(chosen >= 0 && chosen < possibleAttackers.Count()) { bool added = chosenSet.Add(possibleAttackers[chosen]); if(!added) chosenSet.Remove(possibleAttackers[chosen]); } else { Console.Write("Select a number from -1 to "); Console.WriteLine(possibleAttackers.Count() - 1); } PrintChosenCreatures(chosenSet); continue; } ParseCommands(input); } return chosenSet; }
/// <summary> /// Constructor. /// </summary> public TestClassTableEntry( TestClass testClass, bool emphasized, IList<TestResult> testResults, Func<TestResult, string> testUrlBuilder) { Name = GetColoredText("black", testClass.DisplayName, emphasized, preventWrapping: true); PassCount = testResults.Count(result => result.Succeeded); FailCount = testResults.Count(result => !result.Succeeded); TotalCount = testResults.Count; TestResults = testResults.Select ( result => new TestResultTableEntry(result, testUrlBuilder) ).ToList(); }
public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand) { int i; // check if the params number 4, that the number/sides are integers, and that number and sides are both greater than 0 if (paramList.Count() == 3 && Int32.TryParse(paramList[1], out i) && Int32.TryParse(paramList[2], out i) && (Int32.Parse(paramList[1]) > 0) && (Int32.Parse(paramList[2]) > 0) && (Int32.Parse(paramList[1]) <= 4) && (Int32.Parse(paramList[2]) <= 100)) { var dice = Int32.Parse(paramList[1]); var sides = Int32.Parse(paramList[2]); var random = new Random(); var diceList = new List<int>(); for (var j = 0; j < dice; j++) { diceList.Add(random.Next(1, sides)); } var outputString = String.Format("Rolling a {0} sided die, {1} time{2}: {3}", sides, dice, (dice > 1) ? "s" : "", diceList.Aggregate("", (current, roll) => current + roll + " ").Trim()); Utils.SendChannel(outputString); } else { Utils.SendChannel("Usage: !dice <number 1-4 > <sides 1 - 100>"); } }
public async Task <bool> UpdateAsync(ApplicationUser <TKey> user, IList <IdentityUserClaim <TKey> > claims, IList <IdentityUserRole <TKey> > roles, IList <IdentityUserLogin <TKey> > logins, IList <IdentityUserToken <TKey> > tokens) { const string updateUserSql = "UPDATE [dbo].[Users] SET UserName = @UserName, NormalizedUserName = @NormalizedUserName, Email = @Email, NormalizedEmail = @NormalizedEmail," + "EmailConfirmed = @EmailConfirmed, PasswordHash = @PasswordHash, SecurityStamp = @SecurityStamp, ConcurrencyStamp = @ConcurrencyStamp, PhoneNumber = @PhoneNumber, PhoneNumberConfirmed = @PhoneNumberConfirmed, " + "TwoFactorEnabled = @TwoFactorEnabled, LockoutEnd = @LockoutEnd, LockoutEnabled = @LockoutEnabled, AccessFailedCount = @AccessFailedCount, FirstName = @FirstName, SecondName = @SecondName" + "WHERE [Id] = @Id;"; using (var transaction = _connection.BeginTransaction()) { await _connection.ExecuteAsync(updateUserSql, user, transaction); if (claims?.Count() > 0) { const string deleteClaimSql = "DELETE FROM [dbo].[UserClaims] WHERE [UserId] = @userId"; await _connection.ExecuteAsync(deleteClaimSql, new { UserId = user.Id }, transaction); const string insertClaimSql = "INSER INTO [dbo].[UserClaims] (UserId, ClaimType, ClaimValues) VALUES (@UserId, @ClaimType, @ClaimValues)"; await _connection.ExecuteAsync(insertClaimSql, claims, transaction); } if (roles?.Count() > 0) { const string deleteRoleSql = "DELETE FROM [dbo].[UserRoles] WHERE [UserId] = @userId"; await _connection.ExecuteAsync(deleteRoleSql, new { UserId = user.Id }, transaction); const string insertRoleSql = "INSER INTO [dbo].[UserRoles] (RoleId, ClaimType, ClaimValues) VALUES (@RoleId, @ClaimType, @ClaimValues)"; await _connection.ExecuteAsync(insertRoleSql, roles, transaction); } if (tokens?.Count() > 0) { const string deleteTokenSql = "DELETE FROM [dbo].[UserTokens] WHERE [UserId] = @userId"; await _connection.ExecuteAsync(deleteTokenSql, new { UserId = user.Id }, transaction); const string insertTokenSql = "INSER INTO [dbo].[UserToken] VALUES (@UserId, @LoginProvider, @Name, @Value);"; await _connection.ExecuteAsync(insertTokenSql, tokens, transaction); } if (logins?.Count() > 0) { const string deleteLoginSql = "DELETE FROM [dbo].[UserLogins] WHERE [UserId] = @userId"; await _connection.ExecuteAsync(deleteLoginSql, new { UserId = user.Id }, transaction); const string insertTokenSql = "INSER INTO [dbo].[UserToken] VALUES (@LoginProvider, @ProviderKey, @ProviderDisplayName, @UserId);"; await _connection.ExecuteAsync(insertTokenSql, tokens, transaction); } try { transaction.Commit(); } catch { transaction.Rollback(); return(false); } } return(true); }
/// <summary> /// Orders selected point list as a square matrix /// </summary> /// <param name="selectedPoints">Selected points list</param> /// <returns>Ordered in matrix order list</returns> protected virtual IList<SelectedPoint> OrderAsMatrix(IList<SelectedPoint> selectedPoints) { var sortedList = new List<SelectedPoint>(); var selected = selectedPoints.Select(x => x).ToList(); var matrixDimension = (int)Math.Sqrt(selectedPoints.Count()); if (matrixDimension * matrixDimension != selected.Count) { return selectedPoints; } for (int i = 0; i < matrixDimension; i++) { //take each sqrt(elementCount) topmost elements from original list, order them by X coordinate, //add to new list and remove from original sortedList.AddRange( selected .OrderBy(point => point.Location.Y) .Take(matrixDimension) .OrderBy(point => point.Location.X)); foreach (var item in sortedList) { selected.Remove(item); } } return sortedList; }
public static Schedule Empty = new Schedule(); // Null object pattern /// <summary> /// Creates an instance of <see cref="Schedule"/> from carrier mouvements. /// </summary> /// <param name="carrierMovements"></param> public Schedule(IList<CarrierMovement> carrierMovements) { // check if not null if (carrierMovements == null) throw new ArgumentNullException("carrierMovements"); // no null elements if (carrierMovements.Count() > 0 && carrierMovements.ToList().Exists(carrierMovement => carrierMovement == null)) throw new ArgumentException("carrierMovements contains null elements."); // no elements if (carrierMovements.Count() == 0) throw new ArgumentException("carrierMovements has no elements."); _carrierMouvements = carrierMovements; }
public bool Start(HostControl hostControl) { _log.InfoFormat("Starting Subscriber Activity Service"); var started = new List<ServiceControl>(); try { _services = _serviceBootstrappers.Select(x => x.CreateService()).ToList(); _log.InfoFormat("Starting {0} services", _services.Count()); foreach (ServiceControl activityService in _services) { hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1)); StartService(hostControl, activityService); started.Add(activityService); } return true; } catch (Exception ex) { _log.Error("Service failed to start", ex); Parallel.ForEach(started, service => { hostControl.RequestAdditionalTime(TimeSpan.FromMinutes(1)); StopService(hostControl, service); }); throw; } }
public InterlockDataAdapter(OleDbDataReader dr ,IList<string> dynamicList, int startColumn) { ControlSystemName = string.Empty; InterlockTypeName = Number = string.Empty; Cause = string.Empty; Description = string.Empty; ControlSystemName = dr.SafeString((int)InterlockColumn.ControlSystemName).Trim(); InterlockTypeName = dr.SafeString((int)InterlockColumn.InterlockType).Trim(); Number = dr.SafeString((int)InterlockColumn.Number).Trim(); Cause = dr.SafeString((int)InterlockColumn.Cause).Trim(); Description = dr.SafeString((int)InterlockColumn.Description).Trim(); DynamicProperties = new List<DynamicProperty>(); if (dynamicList != null && dynamicList.Any()) { for (int d = 0; d < dynamicList.Count(); d++) { string p = dynamicList[d]; DynamicProperty property = new DynamicProperty(); property.PropertyName = p; property.PropertyValue = dr.SafeString(startColumn + d); DynamicProperties.Add(property); } } }
public async Task AddMenus(IList <Menu> menus, Guid userID, string userName) { if ((menus?.Count() ?? 0) == 0L) { return; } foreach (var menu in menus) { var param = new DynamicParameters(); param.Add("Scheme", menu.Scheme); param.Add("Text", menu.Text); param.Add("SubText", menu.SubText); param.Add("ChangeType", menu.ChangeType); param.Add("RequestID", menu.RequestID); param.Add("Undeclared", menu.Undeclared); param.Add("@Approved", menu.Approved); param.Add("@Remarks", menu.Remarks); param.Add("@ReviewedBy", userID); param.Add("@ReviewedByName", userName); await SqlMapper.ExecuteAsync(_unitOfWork.Connection, "AddMenus", param, commandType : CommandType.StoredProcedure, transaction : _unitOfWork.Transaction); } }
private static int CalculateTotalFromTokens(IList<string> tokens) { var total = int.Parse(tokens[0]); for (var i = 1; (i + 1) < tokens.Count(); i += 2) { var right = int.Parse(tokens[i + 1]); switch (tokens[i]) { case "a" : total += right; break; case "b" : total -= right; break; case "c" : total *= right; break; case "d" : total /= right; break; } } return total; }
internal void PushDataToDataBase(IList <DataChunk> chunkList) { try { if ((chunkList?.Count() ?? 0) == 0) { return; } _log?.Verbose($"Saving {chunkList.Count()} records"); using (var cn = DbConnection()) { cn.Open(); using (var trans = cn.BeginTransaction()) { foreach (var chunk in chunkList) { cn.Query(@"INSERT INTO UserGets (VkontakteUserId, Timestamp, CompressedUserGet) VALUES (@VkontakteUserId, @Timestamp, @CompressedUserGet);", chunk); } trans.Commit(); } } } catch (Exception ex) { _log?.Error(ex, ex.Message); } }
/// <summary> /// Style a prompt and populate the message based on <see cref="PromptStyler.PromptStyle"/>. /// </summary> /// <typeparam name="T"> The type of the options.</typeparam> /// <param name="message"> The message that will contain the prompt.</param> /// <param name="prompt"> The prompt.</param> /// <param name="options"> The options.</param> /// <remarks> /// <typeparamref name="T"/> should implement <see cref="object.ToString"/>. /// </remarks> public virtual void Apply <T>(ref Message message, string prompt, IList <T> options) { SetField.CheckNull(nameof(prompt), prompt); SetField.CheckNull(nameof(options), options); switch (PromptStyle) { case PromptStyle.Auto: message.Text = prompt; message.AddButtons(options); break; case PromptStyle.AutoText: Apply(ref message, prompt, options, options?.Count() > 4 ? PromptStyle.PerLine : PromptStyle.Inline); break; case PromptStyle.Inline: //TODO: Refactor buildlist function to a more generic namespace when changing prompt to use recognizers. message.Text = $"{prompt} {FormFlow.Advanced.Language.BuildList(options.Select(option => option.ToString()), Resources.DefaultChoiceSeparator, Resources.DefaultChoiceLastSeparator)}"; break; case PromptStyle.PerLine: message.Text = $"{prompt}\n{FormFlow.Advanced.Language.BuildList(options.Select(option => $"* {option.ToString()}"), "\n", "\n")}"; break; case PromptStyle.None: default: message.Text = prompt; break; } }
/// <summary> /// Given an input feature, a feature space and its associated labels, and a positive integer 'k', /// Determines the 'k' nearest neighbor label for the input feature. The 'k' value corresponds /// to the number of nearest neighbors to use in the voting process. /// /// <remarks> /// "When I have this grid of data points, and I provide one additional example row, find the 'k' number /// of rows that are most similar, count up the number of occurrences of each label for each row (1 to 'k'), /// and choose the label with the highest occurrence." /// </remarks> /// <see href="http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm" /> /// </summary> /// <param name="distanceType">The type of equation to use when measuring the distance between each data point</param> /// <param name="input">The matrix row to input; must have the same number of columns as the feature space</param> /// <param name="featureSpace">The feature space matrix; everything we know</param> /// <param name="labels">The results for each feature space row; what we call each collection of data points</param> /// <param name="k">The number of nearest neighbors to include in the voting; the label with the most occurrences in 'k' neighbors wins</param> /// <returns></returns> public static string Classify(DistanceType distanceType, Number[] input, Matrix featureSpace, IList<string> labels, int k) { if (labels.Count() != featureSpace.Rows) { throw new ArgumentException("The number of labels must match the number of rows of data in the feature space", "labels"); } var distances = CalculateDistances(distanceType, featureSpace, input); var nearestNeighbors = distances.OrderByDescending(d => d.Value).Take(k); var votes = new Dictionary<string, int>(k); foreach (var label in nearestNeighbors.Select(neighbor => labels[neighbor.Key])) { if (votes.ContainsKey(label)) { votes[label]++; } else { votes.Add(label, 1); } } var nearest = votes.OrderByDescending(v => v.Value).First().Key; return nearest; }
private void Init(IList<Point> vertices ) { if (vertices == null || vertices.Count() < 2) throw new ArgumentException("vertices being passed to create line is not valid."); Vertices = new List<Point>(vertices); }
public IList<TreeNode> BuidTree(IList<TreeNode> treeList, IList<Resource> list, IList<Resource> listall) { foreach (var li in list) { var count = listall.Count(r => r.F_ResourceID.Equals(li.ResourceID)); if (count == 0) { TreeFile treeFile = new TreeFile(); treeFile.text = li.ResourcName; treeFile.id = li.ResourceID; treeFile.url = li.URL; treeList.Add(treeFile); } else { TreeFolder treefolder = new TreeFolder(); var TempList = listall.Where(s => s.F_ResourceID.Equals(li.ResourceID)); treefolder.id = li.ResourceID; treefolder.url = li.URL; treefolder.text = li.ResourcName; IList<TreeNode> listchild = new List<TreeNode>(); treefolder.children = BuidTree(listchild, TempList.ToList(), listall); treeList.Add(treefolder); } } return treeList; }
/// <summary> /// Joins the specified lists. /// </summary> /// <param name="xList">The list with the propertie x active.</param> /// <param name="yList">The list with the propertie y active.</param> /// <param name="group">The group aplicable to each element.</param> /// <returns>The joined list</returns> private static IEnumerable<OutputClass> Join(IList<InputClass> xList, IList<InputClass> yList, string group) { var outputObject = new OutputClass() { ClassAB = group, Y = 0, X = 0 }; var countX = xList.Count(); var countY = yList.Count(); var count = countY > countX ? countY : countX; var array = Enumerable.Repeat(outputObject, count).ToArray(); var iteratorX = new Iterator(xList); var iteratorY = new Iterator(yList); foreach (var outputClass in array) { outputClass.X = iteratorX.Next().Codigo; outputClass.Y = iteratorY.Next().Codigo; outputClass.ClassAB = group; } return array; }
/// <summary> /// Retrives the width columns. /// </summary> /// <param name="columns">The columns.</param> /// <returns>Dictionary{System.StringSystem.Int32}.</returns> private static Dictionary<string, int> RetriveWidthColumns(IList<string> columns) { var columnWidthList = new Dictionary<string, int>(); if (columns != null && columns.Any()) { if (columns[0].Contains(Constants.SplitVerticalBar)) { for (var i = 0; i < columns.Count(); i++) { var column = columns[i].Split(Constants.SplitVerticalBar); var columnUniqName = !string.IsNullOrEmpty(column[0]) ? column[0] : string.Empty; var columnWidth = 0; try { columnWidth = !string.IsNullOrEmpty(column[1]) && column[1].Length > 1 ? Convert.ToInt32(column[1], CultureInfo.InvariantCulture) : 0; } catch { } columnWidthList[columnUniqName.Trim()] = columnWidth; } } } return columnWidthList; }
public void FancyTable(IList<string> headers) { SetFillColor(255, 0, 0); SetTextColor(255); SetDrawColor(128, 0, 0); SetLineWidth(0.3); SetFont("", "B"); int[] w = { 40, 35, 40, 45 }; for (int i = 0; i < headers.Count(); i++) { Cell(w[i], 7, headers[i], "1", 0, AlignEnum.Center, true); } Ln(); SetFillColor(224, 235, 255); SetTextColor(0); SetFont(""); bool fill = false; foreach (var row in Data) { Cell(w[0], 6, row[0], "LR", 0, AlignEnum.Left, fill); Cell(w[1], 6, row[1], "LR", 0, AlignEnum.Left, fill); Cell(w[2], 6, string.Format("{0:N0}", Convert.ToInt32(row[2])), "LR", 0, AlignEnum.Right, fill); Cell(w[3], 6, string.Format("{0:N0}", Convert.ToInt32(row[3])), "LR", 0, AlignEnum.Right, fill); Ln(); fill = !fill; } Cell(w.Sum(), 0, "", "T"); }
public void AddPeriod(int recap, int minutes, int review, string title = "Pomodoro") { var order = _periods?.Count() ?? 0; var period = new Period(Guid.NewGuid(), title, order, recap, minutes, review, PeriodType.Period, null); _periods.Add(period); }
/// <inheritdoc/> public virtual async Task <IdentityResult> UpdateAsync(TUser user, IList <TUserClaim> claims, IList <TUserRole> roles, IList <TUserLogin> logins, IList <TUserToken> tokens) { const string updateUserSql = "UPDATE [dbo].[AspNetUsers] " + "SET [UserName] = @UserName, [NormalizedUserName] = @NormalizedUserName, [Email] = @Email, [NormalizedEmail] = @NormalizedEmail, [EmailConfirmed] = @EmailConfirmed, " + "[PasswordHash] = @PasswordHash, [SecurityStamp] = @SecurityStamp, [ConcurrencyStamp] = @ConcurrencyStamp, [PhoneNumber] = @PhoneNumber, " + "[PhoneNumberConfirmed] = @PhoneNumberConfirmed, [TwoFactorEnabled] = @TwoFactorEnabled, [LockoutEnd] = @LockoutEnd, [LockoutEnabled] = @LockoutEnabled, " + "[AccessFailedCount] = @AccessFailedCount " + "WHERE [Id] = @Id;"; using (var transaction = DbConnection.BeginTransaction()) { await DbConnection.ExecuteAsync(updateUserSql, new { user.UserName, user.NormalizedUserName, user.Email, user.NormalizedEmail, user.EmailConfirmed, user.PasswordHash, user.SecurityStamp, user.ConcurrencyStamp, user.PhoneNumber, user.PhoneNumberConfirmed, user.TwoFactorEnabled, user.LockoutEnd, user.LockoutEnabled, user.AccessFailedCount, user.Id }, transaction); if (claims?.Count() > 0) { await ReplaceClaims(claims, user.Id, transaction); } if (roles?.Count() > 0) { await ReplaceRoles(roles, user.Id, transaction); } if (logins?.Count() > 0) { await ReplaceLogins(logins, user.Id, transaction); } if (tokens?.Count() > 0) { await ReplaceTokens(tokens, user.Id, transaction); } try { transaction.Commit(); } catch { transaction.Rollback(); return(IdentityResult.Failed(new IdentityError { Code = string.Empty, Description = $"User '{user.UserName}' could not be updated." })); } } return(IdentityResult.Success); }
private static IList <DailyStatsViewData> BuildDisciplineStats(IList <StudentInfractionInfo> studentInfractions, IList <Date> allSchoolDays) { var res = new List <DailyStatsViewData>(); foreach (var day in allSchoolDays.Select(d => d.Day)) { var infractionsCount = studentInfractions?.Count(x => x.OccurrenceDate == day.Date) ?? 0; res.Add(DailyStatsViewData.Create(day.Date, infractionsCount, "MMM yyyy")); } return(res); }
/// <summary> /// Agrega uno o varios mensajes al resultado. /// </summary> /// <param name="messages">Lista de mensajes de error.</param> /// <returns>ErrorOptions.</returns> public ErrorOptions WithMessages(IList <string> messages) { if (messages?.Count() > 0) { foreach (var message in messages) { WithMessages(message); } } return(this); }
/// <inheritdoc /> public virtual async Task <bool> UpdateAsync(TRole role, IList <TRoleClaim> claims = null) { var updateRoleSql = $"update {TN("Roles")} " + $"set {CN("Name")} = @Name, " + $"{CN("NormalizedName")} = @NormalizedName, " + $"{CN("ConcurrencyStamp")} = @ConcurrencyStamp " + $"where {CN("Id")} = {GID("Id")};"; using (var transaction = DbConnection.BeginTransaction()) { await DbConnection.ExecuteAsync(updateRoleSql, new { role.Name, role.NormalizedName, role.ConcurrencyStamp, role.Id }, transaction); if (claims?.Count() > 0) { var deleteClaimsSql = "delete " + $"from {TN("RoleClaims")} " + $"where {CN("RoleId")} = {GID("RoleId")};"; await DbConnection.ExecuteAsync(deleteClaimsSql, new { RoleId = role.Id }, transaction); var insertClaimsSql = $"insert into {TN("RoleClaims")} ({CN("RoleId")}, {CN("ClaimType")}, {CN("ClaimValue")}) " + $"values ({GID("RoleId")}, @ClaimType, @ClaimValue);"; await DbConnection.ExecuteAsync(insertClaimsSql, claims.Select(x => new { RoleId = role.Id, x.ClaimType, x.ClaimValue }), transaction); } try { transaction.Commit(); } catch { transaction.Rollback(); return(false); } } return(true); }
/// <inheritdoc/> public virtual async Task <bool> UpdateAsync(TRole role, IList <TRoleClaim> claims = null) { //const string updateRoleSql = "UPDATE [dbo].[AspNetRoles] " + // "SET [Name] = @Name, [NormalizedName] = @NormalizedName, [ConcurrencyStamp] = @ConcurrencyStamp " + // "WHERE [Id] = @Id;"; string updateRoleSql = sqlAdapter.RolesQuery.UpdateRoleSql <TRole>(); using (var transaction = DbConnection.BeginTransaction()) { await DbConnection.ExecuteAsync(updateRoleSql, new { role.Name, role.NormalizedName, role.ConcurrencyStamp, role.Id }, transaction); if (claims?.Count() > 0) { //const string deleteClaimsSql = "DELETE " + // "FROM [dbo].[AspNetRoleClaims] " + // "WHERE [RoleId] = @RoleId;"; string deleteClaimsSql = sqlAdapter.RolesQuery.DeleteClaimsSql <TRoleClaim>(); await DbConnection.ExecuteAsync(deleteClaimsSql, new { RoleId = role.Id }, transaction); //const string insertClaimsSql = "INSERT INTO [dbo].[AspNetRoleClaims] (RoleId, ClaimType, ClaimValue) " + // "VALUES (@RoleId, @ClaimType, @ClaimValue);"; string insertClaimsSql = sqlAdapter.RolesQuery.InsertClaimsSql <TRoleClaim>(); await DbConnection.ExecuteAsync(insertClaimsSql, claims.Select(x => new { RoleId = role.Id, x.ClaimType, x.ClaimValue }), transaction); } try { transaction.Commit(); } catch { transaction.Rollback(); return(false); } } return(true); }
static IList <string> standardizeArray(IList <string> paths) { if (paths?.Count() > 0) { var newPaths = new List <string>(); foreach (var item in paths) { newPaths.Add(item.StandardizeDirectorySeparator()); } return(newPaths); } return(paths); }
public override async Task <bool> UpdateAsync(ExtendedIdentityRole role, IList <IdentityRoleClaim <string> > claims = null) { const string updateRoleSql = "UPDATE [dbo].[AspNetRoles] " + "SET [Name] = @Name, [NormalizedName] = @NormalizedName, [ConcurrencyStamp] = @ConcurrencyStamp, [Description] = @Description " + "WHERE [Id] = @Id;"; using (var transaction = DbConnection.BeginTransaction()) { await DbConnection.ExecuteAsync(updateRoleSql, new { role.Name, role.NormalizedName, role.ConcurrencyStamp, role.Description, role.Id }, transaction); if (claims?.Count() > 0) { const string deleteClaimsSql = "DELETE " + "FROM [dbo].[AspNetRoleClaims] " + "WHERE [RoleId] = @RoleId;"; await DbConnection.ExecuteAsync(deleteClaimsSql, new { RoleId = role.Id }, transaction); const string insertClaimsSql = "INSERT INTO [dbo].[AspNetRoleClaims] (RoleId, ClaimType, ClaimValue) " + "VALUES (@RoleId, @ClaimType, @ClaimValue);"; await DbConnection.ExecuteAsync(insertClaimsSql, claims.Select(x => new { RoleId = role.Id, x.ClaimType, x.ClaimValue }), transaction); } try { transaction.Commit(); } catch { transaction.Rollback(); return(false); } } return(true); }
public AvaliaProbabilidadeMao(IList <Carta> mao, IList <Carta> maoSecundaria, IList <Carta> mesa, uint numeroRodadas = 100000) { Deck = new DeckA(); Deck.CriaDeckAvaliacao(); MaoPrincipal = new CartaA[LIMITE_MAO_P]; MaoSecundaria = new CartaA[LIMITE_MAO_S]; Mesa = new CartaA[LIMITE_MESA]; ToCartaA(mao, MaoPrincipal); ToCartaA(maoSecundaria, MaoSecundaria); ToCartaA(mesa, Mesa); NumCartasMao = mao?.Count(p => p != null) ?? 0; NumCartasMaoSec = maoSecundaria?.Count(p => p != null) ?? 0; NumCartasMesa = mesa?.Count(p => p != null) ?? 0; NumeroRodadas = numeroRodadas; }
public async Task <int> SaveMovieAsync(Movie Movie, IList <GenreType> SelectedGenres = null) { if (Movie == null) { return(0); } if (SelectedGenres?.Count() > 0) { foreach (var item in SelectedGenres) { var g = new Genre(item); Movie.Genres.Add(g); } } var requestUrl = "http://localhost:5000/api/media/item/" + Movie.ID; var response = await _httpClient.PutAsync(requestUrl, new StringContent(JsonConvert.SerializeObject(Movie), Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) { return(0); } try { if (int.TryParse(await response.Content.ReadAsStringAsync(), out int result)) { return(result); } else { return(0); } } catch { return(0); } }
/// <inheritdoc/> public virtual async Task <IdentityResult> UpdateAsync(TRole role, IList <TRoleClaim> claims = null) { const string updateRoleSql = "UPDATE [dbo].[AspNetRoles] " + "SET [Name] = @Name, [NormalizedName] = @NormalizedName, [ConcurrencyStamp] = @ConcurrencyStamp " + "WHERE [Id] = @Id;"; using (var transaction = DbConnection.BeginTransaction()) { await DbConnection.ExecuteAsync(updateRoleSql, new { role.Name, role.NormalizedName, role.ConcurrencyStamp, role.Id }, transaction); if (claims?.Count() > 0) { const string deleteClaimsSql = "DELETE " + "FROM [dbo].[AspNetRoleClaims] " + "WHERE [RoleId] = @RoleId;"; await DbConnection.ExecuteAsync(deleteClaimsSql, new { RoleId = role.Id }, transaction); const string insertClaimsSql = "INSERT INTO [dbo].[AspNetRoleClaims] (RoleId, ClaimType, ClaimValue) " + "VALUES (@RoleId, @ClaimType, @ClaimValue);"; await DbConnection.ExecuteAsync(insertClaimsSql, claims.Select(x => new { RoleId = role.Id, x.ClaimType, x.ClaimValue }), transaction); } try { transaction.Commit(); } catch { transaction.Rollback(); return(IdentityResult.Failed(new IdentityError { Code = string.Empty, Description = $"Role '{role.Name}' could not be updated." })); } } return(IdentityResult.Success); }
/// <summary> /// Provide logic for when members other than the bot /// join the conversation, such as your bot's welcome logic. /// </summary> /// <param name="membersAdded">A list of all the members added to the conversation, as /// described by the conversation update activity.</param> /// <param name="turnContext">A strongly-typed context object for this turn.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks> /// When the <see cref="OnConversationUpdateActivityAsync(ITurnContext{IConversationUpdateActivity}, CancellationToken)"/> /// method receives a conversation update activity that indicates one or more users other than the bot /// are joining the conversation, it calls this method. /// </remarks> protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { if (membersAdded?.Count() > 0) { var message = turnContext.Activity; string myBotId = message.Recipient.Id; string teamId = message.Conversation.Id; var teamsChannelData = message.GetChannelData <TeamsChannelData>(); foreach (var member in membersAdded) { if (member.Id == myBotId) { this.telemetryClient.TrackTrace($"Bot installed to team {teamId}"); var properties = new Dictionary <string, string> { { "Scope", message.Conversation?.ConversationType }, { "TeamId", teamId }, { "InstallerId", message.From.Id }, }; this.telemetryClient.TrackEvent("AppInstalled", properties); // Try to determine the name of the person that installed the app, which is usually the sender of the message (From.Id) // Note that in some cases we cannot resolve it to a team member, because the app was installed to the team programmatically via Graph var personThatAddedBot = (await this.conversationHelper.GetMemberAsync(turnContext, message.From.Id, cancellationToken))?.Name; await this.SaveAddedToTeam(message.ServiceUrl, teamId, teamsChannelData.Tenant.Id, personThatAddedBot); await this.WelcomeTeam(turnContext, personThatAddedBot, cancellationToken); } else { this.telemetryClient.TrackTrace($"New member {member.Id} added to team {teamsChannelData.Team.Id}"); await this.WelcomeUser(turnContext, member.Id, teamsChannelData.Tenant.Id, teamsChannelData.Team.Id, cancellationToken); } } } await base.OnMembersAddedAsync(membersAdded, turnContext, cancellationToken); }
public async Task BulkAddReview(IList <Menu> menus, Guid userID, string userName) { if ((menus?.Count() ?? 0) == 0L) { return; } foreach (var menu in menus) { var param = new DynamicParameters(); param.Add("@ID", menu.ID); param.Add("@Approved", menu.Approved); param.Add("@Remarks", menu.Remarks); param.Add("@ReviewedBy", userID); param.Add("@ReviewedByName", userName); await SqlMapper.ExecuteAsync(_unitOfWork.Connection, "AddMenuReview", param, commandType : CommandType.StoredProcedure, transaction : _unitOfWork.Transaction); } }
public async Task BulkUpdate(IList <Menu> menus, Guid userID, string userName) { if ((menus?.Count() ?? 0) == 0L) { return; } foreach (var menu in menus) { var param = new DynamicParameters(); param.Add("@ID", menu.ID); param.Add("@Scheme", menu.Scheme); param.Add("@Text", menu.Text); param.Add("@SubText", menu.SubText); param.Add("@ChangeType", menu.ChangeType); await SqlMapper.ExecuteAsync(_unitOfWork.Connection, "UpdateMenu", param, commandType : CommandType.StoredProcedure, transaction : _unitOfWork.Transaction); } }
public void AddReply(IList <Tweet> tweets) { var cnt = tweets?.Count() ?? 0; if (cnt == 0) { return; } if (cnt == 1) { #pragma warning disable CS8602 // 僕のnull合体演算子にVisualStudioがついてこれなかった var t = tweets[0]; #pragma warning restore CS8602 // InReplyTo.Value = t.IsRetweetedTweet ? t.RetweetedId : t.Id; InReplyToMessage.Value = t.FullText; } var reply = tweets.Select(t => "@" + t.ScreenName) .Distinct() .Append(Text.Value); Text.Value = string.Join(' ', reply); }
public static IList <object[]> GetSpecTestDetails() { if (_specTests == null) { _specTests = new List <SchemaSpecTest>(); // get test files location relative to the test project dll string baseTestPath = ResolvePath(Path.Combine("Specs", "tests")) + @"\"; string[] testFiles = Directory.GetFiles(baseTestPath, "*.json", SearchOption.AllDirectories); #if (PORTABLE || NET35) testFiles = testFiles.Where(f => !f.EndsWith("bignum.json")).ToArray(); testFiles = testFiles.Where(f => !f.EndsWith("format.json")).ToArray(); #endif testFiles = testFiles.Where(f => !f.EndsWith("non-bmp-regex.json")).ToArray(); testFiles = testFiles.Where(f => !f.EndsWith("ecmascript-regex.json")).ToArray(); testFiles = testFiles.Where(f => !f.EndsWith("float-overflow.json")).ToArray(); // todo - add support for all formats testFiles = testFiles.Where(f => !f.EndsWith("content.json") && !f.EndsWith("idn-email.json") && !f.EndsWith("idn-hostname.json") && !f.EndsWith("iri-reference.json") && !f.EndsWith("iri.json") && !f.EndsWith("relative-json-pointer.json")).ToArray(); // read through each of the *.json test files and extract the test details foreach (string testFile in testFiles) { string relativePath = MakeRelativePath(baseTestPath, testFile); string version = relativePath.Split('\\').First(); string testJson = System.IO.File.ReadAllText(testFile); JsonTextReader testJsonReader = new JsonTextReader(new StringReader(testJson)); testJsonReader.FloatParseHandling = testFile.EndsWith("const.json") ? FloatParseHandling.Decimal : FloatParseHandling.Double; JArray a = (JArray)JToken.ReadFrom(testJsonReader); foreach (JObject testCase in a) { foreach (JObject test in testCase["tests"]) { SchemaSpecTest schemaSpecTest = new SchemaSpecTest(); schemaSpecTest.FileName = Path.GetFileName(testFile); schemaSpecTest.Version = version; schemaSpecTest.TestCaseDescription = (string)testCase["description"]; schemaSpecTest.Schema = testCase["schema"]; schemaSpecTest.TestDescription = (string)test["description"]; schemaSpecTest.Data = test["data"]; schemaSpecTest.IsValid = (bool)test["valid"]; schemaSpecTest.TestNumber = _specTests.Count(t => t.Version == schemaSpecTest.Version) + 1; #if NET35 // Uri class in .NET Framework 2.0 doesn't like the uri in this test if ((schemaSpecTest.FileName == "format.json" || schemaSpecTest.FileName == "uri.json") && schemaSpecTest.TestDescription == "a valid URL ") { continue; } #endif _specTests.Add(schemaSpecTest); } } } } return(_specTests.Select(s => new object[] { s }).ToList()); }
public void process(List <int?> selected, IRequestUow Uow) { //------------ if (selected != null) { for (int w = 0; w < selected.Count; w++) { var requestList = Uow.Requests.GetAllIncludeRequest().ToList().Where(x => x.Accepted == false && x.LankymoData == LankymoData).ToList(); IList <AlgorithmDataModel> data = ConstructData(requestList, Uow); AllRequests = data; PasirinktasDarzelis = selected[w]; AllRequests = AllRequests.OrderByDescending(p => p.PrioritetuSuma).ToList(); AllDeclinedRequests = AllRequests; if (PasirinktasDarzelis != null) { var Accepted = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault(); AllAcceptedRequests = new List <AlgorithmDataModel>(); IList <AlgorithmDataModel> AllRequests1 = AllRequests.Where(o => o.PasirinktasDarzelis_1 == PasirinktasDarzelis).ToList(); AllRequests1 = AllRequests1.OrderByDescending(p => p.PrioritetuSuma + p.PreRequestSchool1.DarzelisPrioritetuSuma).ToList(); int k = 0; int length = Accepted.PriemimoVaikuKiekis - k; for (var i = 0; i < length; i++) { if (i >= AllRequests1.Count()) { break; } if (AllRequests1.Count() == 0) { break; } AllAcceptedRequests.Add(AllRequests1[i]); AllDeclinedRequests.Remove(AllRequests1[i]); k++; } Pre_Schools schoolzz = Uow.Schools.GetById(PasirinktasDarzelis.Value); schoolzz.PriemimoVaikuKiekis = schoolzz.PriemimoVaikuKiekis - k; Uow.Schools.Update(schoolzz); for (int v = 0; v < AllAcceptedRequests.Count; v++) { Request update = Uow.Requests.GetById(AllAcceptedRequests[v].Id); update.Accepted = true; update.PriimtasDarzelis = PasirinktasDarzelis; update.PreSchoolAccepted = schoolzz; //update.PreSchool1 = schoolzz; Uow.Requests.Update(update); AllAcceptedRequests[v].Accepted = true; } IList <AlgorithmDataModel> JoinedRequests = new List <AlgorithmDataModel>(); AllDeclinedRequests = AllDeclinedRequests.Where(x => x.PasirinktasDarzelis_1 == PasirinktasDarzelis).ToList(); JoinedRequests = AllAcceptedRequests.Concat(AllDeclinedRequests).ToList(); int vieta = 1; foreach (var req in JoinedRequests) { if (req.PasirinktasDarzelis_1 == PasirinktasDarzelis) { req.PreRequestSchool1.DarzelioVietaEileje = vieta.ToString(); PreRequestSchool update = Uow.PreRequestSchool.GetById(req.PreRequestSchool1.Id); update.DarzelioVietaEileje = vieta.ToString(); Uow.PreRequestSchool.Update(update); } vieta++; } DarzelioPavadinimas = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault().Label; } } for (int w = 0; w < selected.Count; w++) { var requestList = Uow.Requests.GetAllIncludeRequest().ToList().Where(x => x.Accepted == false && x.LankymoData == LankymoData).ToList(); IList <AlgorithmDataModel> data = ConstructData(requestList, Uow); AllRequests = data; PasirinktasDarzelis = selected[w]; AllRequests = AllRequests.OrderByDescending(p => p.PrioritetuSuma).ToList(); AllDeclinedRequests = AllRequests; if (PasirinktasDarzelis != null) { var Accepted = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault(); AllAcceptedRequests = new List <AlgorithmDataModel>(); IList <AlgorithmDataModel> AllRequests1 = AllRequests.Where(o => o.PasirinktasDarzelis_2 == PasirinktasDarzelis && o.Accepted == false).ToList(); AllRequests1 = AllRequests1.OrderByDescending(p => p.PrioritetuSuma + p.PreRequestSchool2.DarzelisPrioritetuSuma).ToList(); int k = 0; int length = Accepted.PriemimoVaikuKiekis - k; for (var i = 0; i < length; i++) { if (i >= AllRequests1.Count()) { break; } if (AllRequests1.Count() == 0) { break; } AllAcceptedRequests.Add(AllRequests1[i]); AllDeclinedRequests.Remove(AllRequests1[i]); k++; } Pre_Schools schoolzz = Uow.Schools.GetById(PasirinktasDarzelis.Value); schoolzz.PriemimoVaikuKiekis = schoolzz.PriemimoVaikuKiekis - k; Uow.Schools.Update(schoolzz); for (int v = 0; v < AllAcceptedRequests.Count; v++) { Request update = Uow.Requests.GetById(AllAcceptedRequests[v].Id); update.Accepted = true; update.PriimtasDarzelis = PasirinktasDarzelis; update.PreSchoolAccepted = schoolzz; Uow.Requests.Update(update); AllAcceptedRequests[v].Accepted = true; } IList <AlgorithmDataModel> JoinedRequests = new List <AlgorithmDataModel>(); List <int> IdList = AllAcceptedRequests.Select(x => x.Id).ToList(); // var requestList2 = Uow.Requests.GetAllIncludeRequest().ToList(); IList <AlgorithmDataModel> data2 = ConstructData(requestList2, Uow); var AllDecRequests = data2.Where(x => x.PasirinktasDarzelis_2 == PasirinktasDarzelis && !IdList.Contains(x.Id) && x.LankymoData == LankymoData).ToList(); var AllacceRequests = AllAcceptedRequests.Concat(AllDecRequests).ToList(); // AllDeclinedRequests = AllDecRequests; JoinedRequests = AllacceRequests; int vieta = data2.Where(x => x.PasirinktasDarzelis_1 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count + 1; foreach (var req in JoinedRequests) { if (req.PasirinktasDarzelis_2 == PasirinktasDarzelis) { req.PreRequestSchool2.DarzelioVietaEileje = vieta.ToString(); PreRequestSchool update = Uow.PreRequestSchool.GetById(req.PreRequestSchool2.Id); update.DarzelioVietaEileje = vieta.ToString(); Uow.PreRequestSchool.Update(update); } vieta++; } DarzelioPavadinimas = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault().Label; } } for (int w = 0; w < selected.Count; w++) { PasirinktasDarzelis = selected[w]; var requestList = Uow.Requests.GetAllIncludeRequest().ToList().Where(x => x.Accepted == false && x.LankymoData == LankymoData).ToList(); IList <AlgorithmDataModel> data = ConstructData(requestList, Uow); AllRequests = data; AllRequests = AllRequests.OrderByDescending(p => p.PrioritetuSuma).ToList(); AllDeclinedRequests = AllRequests; if (PasirinktasDarzelis != null) { var Accepted = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault(); AllAcceptedRequests = new List <AlgorithmDataModel>(); IList <AlgorithmDataModel> AllRequests1 = AllRequests.Where(o => o.PasirinktasDarzelis_3 == PasirinktasDarzelis && o.Accepted == false).ToList(); AllRequests1 = AllRequests1.OrderByDescending(p => p.PrioritetuSuma + p.PreRequestSchool3.DarzelisPrioritetuSuma).ToList(); int k = 0; int length = Accepted.PriemimoVaikuKiekis - k; for (var i = 0; i < length; i++) { if (i >= AllRequests1.Count()) { break; } if (AllRequests1.Count() == 0) { break; } AllAcceptedRequests.Add(AllRequests1[i]); AllDeclinedRequests.Remove(AllRequests1[i]); k++; } Pre_Schools schoolzz = Uow.Schools.GetById(PasirinktasDarzelis.Value); schoolzz.PriemimoVaikuKiekis = schoolzz.PriemimoVaikuKiekis - k; Uow.Schools.Update(schoolzz); for (int v = 0; v < AllAcceptedRequests.Count; v++) { Request update = Uow.Requests.GetById(AllAcceptedRequests[v].Id); update.Accepted = true; update.PriimtasDarzelis = PasirinktasDarzelis; update.PreSchoolAccepted = schoolzz; //update.PreSchool3 = schoolzz; Uow.Requests.Update(update); AllAcceptedRequests[v].Accepted = true; } IList <AlgorithmDataModel> JoinedRequests = new List <AlgorithmDataModel>(); List <int> IdList = AllAcceptedRequests.Select(x => x.Id).ToList(); var requestList2 = Uow.Requests.GetAllIncludeRequest().ToList(); IList <AlgorithmDataModel> data3 = ConstructData(requestList2, Uow); AllDeclinedRequests = data3.Where(x => x.PasirinktasDarzelis_3 == PasirinktasDarzelis && !IdList.Contains(x.Id) && x.LankymoData == LankymoData).ToList(); JoinedRequests = AllAcceptedRequests.Concat(AllDeclinedRequests).ToList(); var kiekis = data3.Where(x => x.PasirinktasDarzelis_1 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count; int vieta = kiekis + data3.Where(x => x.PasirinktasDarzelis_2 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count + 1; foreach (var req in JoinedRequests) { if (req.PasirinktasDarzelis_3 == PasirinktasDarzelis) { req.PreRequestSchool3.DarzelioVietaEileje = vieta.ToString(); PreRequestSchool update = Uow.PreRequestSchool.GetById(req.PreRequestSchool3.Id); update.DarzelioVietaEileje = vieta.ToString(); Uow.PreRequestSchool.Update(update); } vieta++; } DarzelioPavadinimas = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault().Label; } } // for (int w = 0; w < selected.Count; w++) { PasirinktasDarzelis = selected[w]; var requestList = Uow.Requests.GetAllIncludeRequest().ToList(); IList <AlgorithmDataModel> data4 = ConstructData(requestList, Uow); AllRequests = data4.Where(x => x.Accepted == false && x.LankymoData == LankymoData).ToList(); AllRequests = AllRequests.OrderByDescending(p => p.PrioritetuSuma).ToList(); AllDeclinedRequests = AllRequests; if (PasirinktasDarzelis != null) { var Accepted = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault(); AllAcceptedRequests = new List <AlgorithmDataModel>(); IList <AlgorithmDataModel> AllRequests1 = AllRequests.Where(o => o.PasirinktasDarzelis_4 == PasirinktasDarzelis && o.Accepted == false).ToList(); AllRequests1 = AllRequests1.OrderByDescending(p => p.PrioritetuSuma + p.PreRequestSchool4.DarzelisPrioritetuSuma).ToList(); int k = 0; int length = Accepted.PriemimoVaikuKiekis - k; for (var i = 0; i < length; i++) { if (i >= AllRequests1.Count()) { break; } if (AllRequests1.Count() == 0) { break; } AllAcceptedRequests.Add(AllRequests1[i]); AllDeclinedRequests.Remove(AllRequests1[i]); k++; } Pre_Schools schoolzz = Uow.Schools.GetById(PasirinktasDarzelis.Value); schoolzz.PriemimoVaikuKiekis = schoolzz.PriemimoVaikuKiekis - k; Uow.Schools.Update(schoolzz); for (int v = 0; v < AllAcceptedRequests.Count; v++) { Request update = Uow.Requests.GetById(AllAcceptedRequests[v].Id); update.Accepted = true; update.PriimtasDarzelis = PasirinktasDarzelis; update.PreSchoolAccepted = schoolzz; //update.PreSchool4 = schoolzz; Uow.Requests.Update(update); AllAcceptedRequests[v].Accepted = true; } IList <AlgorithmDataModel> JoinedRequests = new List <AlgorithmDataModel>(); List <int> IdList = AllAcceptedRequests.Select(x => x.Id).ToList(); //--- var requestList3 = Uow.Requests.GetAllIncludeRequest().ToList(); IList <AlgorithmDataModel> data5 = ConstructData(requestList3, Uow); AllDeclinedRequests = data5.Where(x => x.PasirinktasDarzelis_4 == PasirinktasDarzelis && !IdList.Contains(x.Id) && x.LankymoData == LankymoData).ToList(); JoinedRequests = AllAcceptedRequests.Concat(AllDeclinedRequests).ToList(); var kiekis = data5.Where(x => x.PasirinktasDarzelis_1 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count; kiekis += data5.Where(x => x.PasirinktasDarzelis_2 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count; int vieta = kiekis + data5.ToList().Where(x => x.PasirinktasDarzelis_3 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count + 1; foreach (var req in JoinedRequests) { if (req.PasirinktasDarzelis_4 == PasirinktasDarzelis) { req.PreRequestSchool4.DarzelioVietaEileje = vieta.ToString(); PreRequestSchool update = Uow.PreRequestSchool.GetById(req.PreRequestSchool4.Id); update.DarzelioVietaEileje = vieta.ToString(); Uow.PreRequestSchool.Update(update); } vieta++; } DarzelioPavadinimas = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault().Label; } } // for (int w = 0; w < selected.Count; w++) { PasirinktasDarzelis = selected[w]; //- var requestList4 = Uow.Requests.GetAllIncludeRequest().ToList(); IList <AlgorithmDataModel> data6 = ConstructData(requestList4, Uow); AllRequests = data6.Where(x => x.Accepted == false && x.LankymoData == LankymoData).ToList(); AllRequests = AllRequests.OrderByDescending(p => p.PrioritetuSuma).ToList(); AllDeclinedRequests = AllRequests; if (PasirinktasDarzelis != null) { var Accepted = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault(); AllAcceptedRequests = new List <AlgorithmDataModel>(); IList <AlgorithmDataModel> AllRequests1 = AllRequests.Where(o => o.PasirinktasDarzelis_5 == PasirinktasDarzelis && o.Accepted == false).ToList(); AllRequests1 = AllRequests1.OrderByDescending(p => p.PrioritetuSuma + p.PreRequestSchool5.DarzelisPrioritetuSuma).ToList(); int k = 0; int length = Accepted.PriemimoVaikuKiekis - k; for (var i = 0; i < length; i++) { if (i >= AllRequests1.Count()) { break; } if (AllRequests1.Count() == 0) { break; } AllAcceptedRequests.Add(AllRequests1[i]); AllDeclinedRequests.Remove(AllRequests1[i]); k++; } Pre_Schools schoolzz = Uow.Schools.GetById(PasirinktasDarzelis.Value); schoolzz.PriemimoVaikuKiekis = schoolzz.PriemimoVaikuKiekis - k; Uow.Schools.Update(schoolzz); for (int v = 0; v < AllAcceptedRequests.Count; v++) { Request update = Uow.Requests.GetById(AllAcceptedRequests[v].Id); update.Accepted = true; update.PriimtasDarzelis = PasirinktasDarzelis; update.PreSchoolAccepted = schoolzz; //update.PreSchool5 = schoolzz; Uow.Requests.Update(update); AllAcceptedRequests[v].Accepted = true; } IList <AlgorithmDataModel> JoinedRequests = new List <AlgorithmDataModel>(); //AllDeclinedRequests = AllDeclinedRequests.Where(x => x.PasirinktasDarzelis_5 == PasirinktasDarzelis).ToList(); //AllDeclinedRequests = Uow.Requests.GetAllIncludeRequest().ToList().Where(x => x.PasirinktasDarzelis_5 == PasirinktasDarzelis && !AllAcceptedRequests.Contains(x)).ToList(); List <int> IdList = AllAcceptedRequests.Select(x => x.Id).ToList(); var requestList5 = Uow.Requests.GetAllIncludeRequest().ToList(); IList <AlgorithmDataModel> data7 = ConstructData(requestList5, Uow); AllDeclinedRequests = data7.Where(x => x.PasirinktasDarzelis_5 == PasirinktasDarzelis && !IdList.Contains(x.Id)).ToList(); JoinedRequests = AllAcceptedRequests.Concat(AllDeclinedRequests).ToList(); var kiekis = data7.Where(x => x.PasirinktasDarzelis_1 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count; kiekis += data7.Where(x => x.PasirinktasDarzelis_2 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count; kiekis += data7.Where(x => x.PasirinktasDarzelis_3 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count; int vieta = kiekis + data7.Where(x => x.PasirinktasDarzelis_4 == PasirinktasDarzelis && x.LankymoData == LankymoData).ToList().Count + 1; foreach (var req in JoinedRequests) { if (req.PasirinktasDarzelis_5 == PasirinktasDarzelis) { req.PreRequestSchool5.DarzelioVietaEileje = vieta.ToString(); PreRequestSchool update = Uow.PreRequestSchool.GetById(req.PreRequestSchool5.Id); update.DarzelioVietaEileje = vieta.ToString(); Uow.PreRequestSchool.Update(update); } vieta++; } DarzelioPavadinimas = AllSchools.Where(x => x.ID == PasirinktasDarzelis).FirstOrDefault().Label; } } } }
/// <inheritdoc/> public virtual async Task <bool> UpdateAsync(TUser user, IList <TUserClaim> claims, IList <TUserRole> roles, IList <TUserLogin> logins, IList <TUserToken> tokens) { const string updateUserSql = "UPDATE [dbo].[AspNetUsers] " + "SET [UserName] = @UserName, [NormalizedUserName] = @NormalizedUserName, [Email] = @Email, [NormalizedEmail] = @NormalizedEmail, [EmailConfirmed] = @EmailConfirmed, " + "[PasswordHash] = @PasswordHash, [SecurityStamp] = @SecurityStamp, [ConcurrencyStamp] = @ConcurrencyStamp, [PhoneNumber] = @PhoneNumber, " + "[PhoneNumberConfirmed] = @PhoneNumberConfirmed, [TwoFactorEnabled] = @TwoFactorEnabled, [LockoutEnd] = @LockoutEnd, [LockoutEnabled] = @LockoutEnabled, " + "[AccessFailedCount] = @AccessFailedCount " + "WHERE [Id] = @Id;"; using (var transaction = DbConnection.BeginTransaction()) { await DbConnection.ExecuteAsync(updateUserSql, new { user.UserName, user.NormalizedUserName, user.Email, user.NormalizedEmail, user.EmailConfirmed, user.PasswordHash, user.SecurityStamp, user.ConcurrencyStamp, user.PhoneNumber, user.PhoneNumberConfirmed, user.TwoFactorEnabled, user.LockoutEnd, user.LockoutEnabled, user.AccessFailedCount, user.Id }, transaction); if (claims?.Count() > 0) { const string deleteClaimsSql = "DELETE " + "FROM [dbo].[AspNetUserClaims] " + "WHERE [UserId] = @UserId;"; await DbConnection.ExecuteAsync(deleteClaimsSql, new { UserId = user.Id }, transaction); const string insertClaimsSql = "INSERT INTO [dbo].[AspNetUserClaims] (UserId, ClaimType, ClaimValue) " + "VALUES (@UserId, @ClaimType, @ClaimValue);"; await DbConnection.ExecuteAsync(insertClaimsSql, claims.Select(x => new { UserId = user.Id, x.ClaimType, x.ClaimValue }), transaction); } if (roles?.Count() > 0) { const string deleteRolesSql = "DELETE " + "FROM [dbo].[AspNetUserRoles] " + "WHERE [UserId] = @UserId;"; await DbConnection.ExecuteAsync(deleteRolesSql, new { UserId = user.Id }, transaction); const string insertRolesSql = "INSERT INTO [dbo].[AspNetUserRoles] (UserId, RoleId) " + "VALUES (@UserId, @RoleId);"; await DbConnection.ExecuteAsync(insertRolesSql, roles.Select(x => new { UserId = user.Id, x.RoleId }), transaction); } if (logins?.Count() > 0) { const string deleteLoginsSql = "DELETE " + "FROM [dbo].[AspNetUserLogins] " + "WHERE [UserId] = @UserId;"; await DbConnection.ExecuteAsync(deleteLoginsSql, new { UserId = user.Id }, transaction); const string insertLoginsSql = "INSERT INTO [dbo].[AspNetUserLogins] (LoginProvider, ProviderKey, ProviderDisplayName, UserId) " + "VALUES (@LoginProvider, @ProviderKey, @ProviderDisplayName, @UserId);"; await DbConnection.ExecuteAsync(insertLoginsSql, logins.Select(x => new { x.LoginProvider, x.ProviderKey, x.ProviderDisplayName, UserId = user.Id }), transaction); } if (tokens?.Count() > 0) { const string deleteTokensSql = "DELETE " + "FROM [dbo].[AspNetUserTokens] " + "WHERE [UserId] = @UserId;"; await DbConnection.ExecuteAsync(deleteTokensSql, new { UserId = user.Id }, transaction); const string insertTokensSql = "INSERT INTO [dbo].[AspNetUserTokens] (UserId, LoginProvider, Name, Value) " + "VALUES (@UserId, @LoginProvider, @Name, @Value);"; await DbConnection.ExecuteAsync(insertTokensSql, tokens.Select(x => new { x.UserId, x.LoginProvider, x.Name, x.Value }), transaction); } try { transaction.Commit(); } catch { transaction.Rollback(); return(false); } } return(true); }
/// <summary> /// Returns a list of curves that represent the profile of an extrusion to be split into material layers, for simple cases. /// </summary> /// <param name="loops">The original CurveLoops representing the extrusion profile.</param> /// <param name="axisCurve">The axis curve used by IfcMaterialLayerUsage to place the IfcMaterialLayers.</param> /// <param name="offsetNorm">The normal used for calculating curve offsets.</param> /// <param name="offset">The offset distance from the axis curve to the material layers, as defined in the IfcMaterialLayerSetUsage "OffsetFromReferenceLine" parameter.</param> /// <param name="totalThickness">The total thickness of all of the generated material layers.</param> /// <returns>A list of curves oriented according to the axis curve.</returns> /// <remarks>The list will contain 4 curves in this order: /// 1. The curve (a bounded Line or an Arc) at the boundary of the first material layer, oriented in the same direction as the Axis curve. /// 2. The line, possibly slanted, representing an end cap and connecting the 1st curve to the 3rd curve. /// 3. The curve (of the same type as the first) at the boundary of the last material layer, oriented in the opposite direction as the Axis curve. /// 4. The line, possibly slanted, representing an end cap and connecting the 3rd curve to the 1st curve. /// Over time, we may increase the number of cases suported.</remarks> private IList <Curve> GetOrientedCurveList(IList <CurveLoop> loops, Curve axisCurve, XYZ offsetNorm, double offset, double totalThickness) { // We are going to limit our attempts to a fairly simple but common case: // 1. 2 bounded curves parallel to the axis curve, of the same type, and either Lines or Arcs. // 2. 2 other edges connecting the two other curves, which are Lines. // This covers most cases and gets rid of issues with highly irregular edges. if (loops.Count() != 1 || loops[0].Count() != 4) { return(null); } // The CreateOffset routine works opposite what IFC expects. For a line, the Revit API offset direction // is the (line tangent) X (the normal of the plane containing the line). In IFC, the (local) line tangent is +X, // the local normal of the plane is +Z, and the positive direction of the offset is +Y. As such, we need to // reverse the normal of the plane to offset in the right direction. Curve offsetAxisCurve = axisCurve.CreateOffset(offset, -offsetNorm); Curve unboundOffsetAxisCurve = offsetAxisCurve.Clone(); unboundOffsetAxisCurve.MakeUnbound(); IList <Curve> originalCurveList = new List <Curve>(); IList <Curve> unboundCurveList = new List <Curve>(); foreach (Curve loopCurve in loops[0]) { originalCurveList.Add(loopCurve); Curve unboundCurve = loopCurve.Clone(); unboundCurve.MakeUnbound(); unboundCurveList.Add(unboundCurve); } int startIndex = -1; bool flipped = false; for (int ii = 0; ii < 4; ii++) { // The offset axis curve should match one of the curves of the extrusion profile. // We check that here by seeing if a point on the offset axis curve is on the current unbounded curve. if (unboundCurveList[ii].Intersect(unboundOffsetAxisCurve) != SetComparisonResult.Overlap && MathUtil.IsAlmostZero(unboundCurveList[ii].Distance(offsetAxisCurve.GetEndPoint(0)))) { startIndex = ii; Transform originalCurveLCS = originalCurveList[ii].ComputeDerivatives(0.0, true); Transform axisCurveLCS = axisCurve.ComputeDerivatives(0.0, true); // We want the first curve to have the same orientation as the axis curve. We will flip the resulting // "curve loop" if not. bool?maybeFlipped = CurvesHaveOppositeOrientation(originalCurveList[ii], axisCurve); if (!maybeFlipped.HasValue) { return(null); } flipped = maybeFlipped.Value; // Now check that startIndex and startIndex+2 are parallel, and totalThickness apart. if ((unboundCurveList[ii].Intersect(unboundCurveList[(ii + 2) % 4]) == SetComparisonResult.Overlap) || !MathUtil.IsAlmostEqual(unboundCurveList[ii].Distance(originalCurveList[(ii + 2) % 4].GetEndPoint(0)), totalThickness)) { return(null); } break; } } // We may want to consider loosening the IsAlmostEqual check above if this fails a lot for seemingly good cases. if (startIndex == -1) { return(null); } IList <Curve> orientedCurveList = new List <Curve>(); for (int ii = 0, currentIndex = startIndex; ii < 4; ii++) { Curve currentCurve = originalCurveList[currentIndex]; if (flipped) { currentCurve = currentCurve.CreateReversed(); } orientedCurveList.Add(currentCurve); currentIndex = flipped ? (currentIndex + 3) % 4 : (currentIndex + 1) % 4; } return(orientedCurveList); }
private int CountUnreadedMessagesForUser(string userId, IList <MessageDto> messages) { return(messages?.Count(m => !m.WasRead && m.UserId != userId) ?? 0); }
protected void Btn_Update_Click(object sender, EventArgs e) { string nick = HttpUtility.UrlDecode(Request.Cookies["nick"].Value); string session = Request.Cookies["nicksession"].Value; TeteShopCategoryService cateDal = new TeteShopCategoryService(); IList <TeteShopInfo> list = CacheCollection.GetNickSessionList().Where(o => o.Short == nick && o.Session == session).ToList(); TeteShopInfo info = null; if (list.Count > 0) { info = list[0]; } if (info == null) { Page.RegisterStartupScript("错误", "<script>alert('您的身份不合法,请确定您已购买!');</script>"); return; } IList <TeteShopCategoryInfo> cateList = cateDal.GetAllTeteShopCategory(Encrypt(nick)); IList <GoodsClassInfo> classList = TaoBaoAPI.GetGoodsClassInfoList(info.Short, session, info.Appkey, info.Appsecret); if (classList == null) { Page.RegisterStartupScript("错误", "<script>alert('获取店铺分类出错!');</script>"); return; } List <TeteShopCategoryInfo> addList = new List <TeteShopCategoryInfo>(); List <TeteShopCategoryInfo> upList = new List <TeteShopCategoryInfo>(); foreach (GoodsClassInfo cinfo in classList) { List <TeteShopCategoryInfo> clist = cateList.Where(o => o.Cateid == cinfo.cid).ToList(); if (clist.Count > 0) { InitCate(nick, cinfo, clist[0]); clist[0].Catecount = classList.Count(o => o.parent_cid == cinfo.cid); upList.Add(clist[0]); } else { TeteShopCategoryInfo ainfo = new TeteShopCategoryInfo(); InitCate(nick, cinfo, ainfo); ainfo.Catecount = classList.Count(o => o.parent_cid == cinfo.cid); addList.Add(ainfo); } } //添加 foreach (TeteShopCategoryInfo cinfo in addList) { cateDal.AddTeteShopCategory(cinfo); } //修改 foreach (TeteShopCategoryInfo cinfo in upList) { cateDal.ModifyTeteShopCategory(cinfo); } //删除 //List<TeteShopCategoryInfo> delList = new List<TeteShopCategoryInfo>(); //foreach (TeteShopCategoryInfo cinfo in cateList) //{ // if (upList.Where(o => o.Cateid == cinfo.Cateid).ToList().Count == 0) // { // delList.Add(cinfo); // } //} //foreach (TeteShopCategoryInfo cinfo in upList) //{ // cateDal.DeleteTeteShopCategory(cinfo.Id); //} //更新商品 ActionGoods(nick, session, info); //更新商品分类包含商品数量 IList <TeteShopCategoryInfo> nowCateList = cateDal.GetAllTeteShopCategory(Encrypt(nick)); TeteShopItemService itemDal = new TeteShopItemService(); for (int i = 0; i < nowCateList.Count; i++) { int count = itemDal.GetItemCountByCId(nowCateList[i].Cateid); nowCateList[i].Catecount = count; } //修改 foreach (TeteShopCategoryInfo cinfo in nowCateList) { cateDal.ModifyTeteShopCategory(cinfo); } Page.RegisterStartupScript("更新提示", "<script>alert('更新成功!');</script>"); }
public int GetLenght() { return(_genes.Count()); }
// This routine may return null geometry for one of three reasons: // 1. Invalid input. // 2. No IfcMaterialLayerUsage. // 3. The IfcMaterialLayerUsage isn't handled. // If the reason is #1 or #3, we want to warn the user. If it is #2, we don't. Pass back shouldWarn to let the caller know. private IList <GeometryObject> CreateGeometryFromMaterialLayerUsage(IFCImportShapeEditScope shapeEditScope, Transform extrusionPosition, IList <CurveLoop> loops, XYZ extrusionDirection, double currDepth, out ElementId materialId, out bool shouldWarn) { IList <GeometryObject> extrusionSolids = null; materialId = ElementId.InvalidElementId; try { shouldWarn = true; // Invalid input. // Check for valid input. if (shapeEditScope == null || extrusionPosition == null || loops == null || loops.Count() == 0 || extrusionDirection == null || !Application.IsValidThickness(currDepth)) { return(null); } IFCProduct creator = shapeEditScope.Creator; if (creator == null) { return(null); } shouldWarn = false; // Missing, empty, or optimized out IfcMaterialLayerSetUsage - valid reason to stop. IIFCMaterialSelect materialSelect = creator.MaterialSelect; if (materialSelect == null) { return(null); } IFCMaterialLayerSetUsage materialLayerSetUsage = materialSelect as IFCMaterialLayerSetUsage; if (materialLayerSetUsage == null) { return(null); } IFCMaterialLayerSet materialLayerSet = materialLayerSetUsage.MaterialLayerSet; if (materialLayerSet == null) { return(null); } IList <IFCMaterialLayer> materialLayers = materialLayerSet.MaterialLayers; if (materialLayers == null || materialLayers.Count == 0) { return(null); } // Optimization: if there is only one layer, use the standard method, with possibly an overloaded material. ElementId baseMaterialId = GetMaterialElementId(shapeEditScope); if (materialLayers.Count == 1) { IFCMaterial oneMaterial = materialLayers[0].Material; if (oneMaterial == null) { return(null); } materialId = oneMaterial.GetMaterialElementId(); if (materialId != ElementId.InvalidElementId) { // We will not override the material of the element if the layer material has no color. if (Importer.TheCache.MaterialsWithNoColor.Contains(materialId)) { materialId = ElementId.InvalidElementId; } } return(null); } // Anything below here is something we should report to the user, with the exception of the total thickness // not matching the extrusion thickness. This would require more analysis to determine that it is actually // an error condition. shouldWarn = true; IList <IFCMaterialLayer> realMaterialLayers = new List <IFCMaterialLayer>(); double totalThickness = 0.0; foreach (IFCMaterialLayer materialLayer in materialLayers) { double depth = materialLayer.LayerThickness; if (MathUtil.IsAlmostZero(depth)) { continue; } if (depth < 0.0) { return(null); } realMaterialLayers.Add(materialLayer); totalThickness += depth; } // Axis3 means that the material layers are stacked in the Z direction. This is common for floor slabs. bool isAxis3 = (materialLayerSetUsage.Direction == IFCLayerSetDirection.Axis3); // For elements extruded in the Z direction, if the extrusion layers don't have the same thickness as the extrusion, // this could be one of two reasons: // 1. There is a discrepancy between the extrusion depth and the material layer set usage calculated depth. // 2. There are multiple extrusions in the body definition. // In either case, we will use the extrusion geometry over the calculated material layer set usage geometry. // In the future, we may decide to allow for case #1 by passing in a flag to allow for this. if (isAxis3 && !MathUtil.IsAlmostEqual(totalThickness, currDepth)) { shouldWarn = false; return(null); } int numLayers = realMaterialLayers.Count(); if (numLayers == 0) { return(null); } // We'll use this initial value for the Axis2 case, so read it here. double baseOffsetForLayer = materialLayerSetUsage.Offset; // Needed for Axis2 case only. The axisCurve is the curve defined in the product representation representing // a base curve (an axis) for the footprint of the element. Curve axisCurve = null; // The oriented cuve list represents the 4 curves of supported Axis2 footprint in the following order: // 1. curve along length of object closest to the first material layer with the orientation of the axis curve // 2. connecting end curve // 3. curve along length of object closest to the last material layer with the orientation opposite of the axis curve // 4. connecting end curve. IList <Curve> orientedCurveList = null; if (!isAxis3) { // Axis2 means that the material layers are stacked inthe Y direction. This is by definition for IfcWallStandardCase, // which has a local coordinate system whose Y direction is orthogonal to the length of the wall. if (materialLayerSetUsage.Direction == IFCLayerSetDirection.Axis2) { axisCurve = GetAxisCurve(creator, extrusionPosition); if (axisCurve == null) { return(null); } orientedCurveList = GetOrientedCurveList(loops, axisCurve, extrusionPosition.BasisZ, baseOffsetForLayer, totalThickness); if (orientedCurveList == null) { return(null); } } else { return(null); // Not handled. } } extrusionSolids = new List <GeometryObject>(); bool positiveOrientation = (materialLayerSetUsage.DirectionSense == IFCDirectionSense.Positive); // Always extrude in the positive direction for Axis2. XYZ materialExtrusionDirection = (positiveOrientation || !isAxis3) ? extrusionDirection : -extrusionDirection; // Axis2 repeated values. // The IFC concept of offset direction is reversed from Revit's. XYZ normalDirectionForAxis2 = positiveOrientation ? -extrusionPosition.BasisZ : extrusionPosition.BasisZ; bool axisIsCyclic = (axisCurve == null) ? false : axisCurve.IsCyclic; double axisCurvePeriod = axisIsCyclic ? axisCurve.Period : 0.0; Transform curveLoopTransform = Transform.Identity; IList <CurveLoop> currLoops = null; double depthSoFar = 0.0; for (int ii = 0; ii < numLayers; ii++) { IFCMaterialLayer materialLayer = materialLayers[ii]; // Ignore 0 thickness layers. No need to warn. double depth = materialLayer.LayerThickness; if (MathUtil.IsAlmostZero(depth)) { continue; } // If the thickness is non-zero but invalid, fail. if (!Application.IsValidThickness(depth)) { return(null); } double extrusionDistance = 0.0; if (isAxis3) { // Offset the curve loops if necessary, using the base extrusionDirection, regardless of the direction sense // of the MaterialLayerSetUsage. double offsetForLayer = positiveOrientation ? baseOffsetForLayer + depthSoFar : baseOffsetForLayer - depthSoFar; if (!MathUtil.IsAlmostZero(offsetForLayer)) { curveLoopTransform.Origin = offsetForLayer * extrusionDirection; currLoops = new List <CurveLoop>(); foreach (CurveLoop loop in loops) { CurveLoop newLoop = CurveLoop.CreateViaTransform(loop, curveLoopTransform); if (newLoop == null) { return(null); } currLoops.Add(newLoop); } } else { currLoops = loops; } extrusionDistance = depth; } else { // startClipCurve, firstEndCapCurve, endClipCurve, secondEndCapCurve. Curve[] outline = new Curve[4]; double[][] endParameters = new double[4][]; double startClip = depthSoFar; double endClip = depthSoFar + depth; outline[0] = orientedCurveList[0].CreateOffset(startClip, normalDirectionForAxis2); outline[1] = orientedCurveList[1].Clone(); outline[2] = orientedCurveList[2].CreateOffset(totalThickness - endClip, normalDirectionForAxis2); outline[3] = orientedCurveList[3].Clone(); for (int jj = 0; jj < 4; jj++) { outline[jj].MakeUnbound(); endParameters[jj] = new double[2]; endParameters[jj][0] = 0.0; endParameters[jj][1] = 0.0; } // Trim/Extend the curves so that they make a closed loop. for (int jj = 0; jj < 4; jj++) { IntersectionResultArray resultArray = null; outline[jj].Intersect(outline[(jj + 1) % 4], out resultArray); if (resultArray == null || resultArray.Size == 0) { return(null); } int numResults = resultArray.Size; if ((numResults > 1 && !axisIsCyclic) || (numResults > 2)) { return(null); } UV intersectionPoint = resultArray.get_Item(0).UVPoint; endParameters[jj][1] = intersectionPoint.U; endParameters[(jj + 1) % 4][0] = intersectionPoint.V; if (numResults == 2) { // If the current result is closer to the end of the curve, keep it. UV newIntersectionPoint = resultArray.get_Item(1).UVPoint; int endParamIndex = (jj % 2); double newParamToCheck = newIntersectionPoint[endParamIndex]; double oldParamToCheck = (endParamIndex == 0) ? endParameters[jj][1] : endParameters[(jj + 1) % 4][0]; double currentEndPoint = (endParamIndex == 0) ? orientedCurveList[jj].GetEndParameter(1) : orientedCurveList[(jj + 1) % 4].GetEndParameter(0); // Put in range of [-Period/2, Period/2]. double newDist = (currentEndPoint - newParamToCheck) % axisCurvePeriod; if (newDist < -axisCurvePeriod / 2.0) { newDist += axisCurvePeriod; } if (newDist > axisCurvePeriod / 2.0) { newDist -= axisCurvePeriod; } double oldDist = (currentEndPoint - oldParamToCheck) % axisCurvePeriod; if (oldDist < -axisCurvePeriod / 2.0) { oldDist += axisCurvePeriod; } if (oldDist > axisCurvePeriod / 2.0) { oldDist -= axisCurvePeriod; } if (Math.Abs(newDist) < Math.Abs(oldDist)) { endParameters[jj][1] = newIntersectionPoint.U; endParameters[(jj + 1) % 4][0] = newIntersectionPoint.V; } } } CurveLoop newCurveLoop = new CurveLoop(); for (int jj = 0; jj < 4; jj++) { if (endParameters[jj][1] < endParameters[jj][0]) { if (!outline[jj].IsCyclic) { return(null); } endParameters[jj][1] += Math.Floor(endParameters[jj][0] / axisCurvePeriod + 1.0) * axisCurvePeriod; } outline[jj].MakeBound(endParameters[jj][0], endParameters[jj][1]); newCurveLoop.Append(outline[jj]); } currLoops = new List <CurveLoop>(); currLoops.Add(newCurveLoop); extrusionDistance = currDepth; } // Determine the material id. IFCMaterial material = materialLayer.Material; ElementId layerMaterialId = (material == null) ? ElementId.InvalidElementId : material.GetMaterialElementId(); // The second option here is really for Referencing. Without a UI (yet) to determine whether to show the base // extusion or the layers for objects with material layer sets, we've chosen to display the base material if the layer material // has no color information. This means that the layer is assigned the "wrong" material, but looks better on screen. // We will reexamine this decision (1) for the Open case, (2) if there is UI to toggle between layers and base extrusion, or // (3) based on user feedback. if (layerMaterialId == ElementId.InvalidElementId || Importer.TheCache.MaterialsWithNoColor.Contains(layerMaterialId)) { layerMaterialId = baseMaterialId; } SolidOptions solidOptions = new SolidOptions(layerMaterialId, shapeEditScope.GraphicsStyleId); // Create the extrusion for the material layer. GeometryObject extrusionSolid = GeometryCreationUtilities.CreateExtrusionGeometry( currLoops, materialExtrusionDirection, extrusionDistance, solidOptions); if (extrusionSolid == null) { return(null); } extrusionSolids.Add(extrusionSolid); depthSoFar += depth; } } catch { // Ignore the specific exception, but let the user know there was a problem processing the IfcMaterialLayerSetUsage. shouldWarn = true; return(null); } return(extrusionSolids); }
/// <summary> /// 保存商品类别(新建或者修改) /// </summary> /// <param name="loggingSessionInfo"></param> /// <param name="itemCategoryInfo"></param> /// <returns></returns> public string SetItemCategoryInfo(LoggingSessionInfo loggingSessionInfo, ItemCategoryInfo itemCategoryInfo) { string strResult = string.Empty; //事物信息 //cSqlMapper.Instance().BeginTransaction(); try { //处理是新建还是修改 if (itemCategoryInfo.Item_Category_Id == null || itemCategoryInfo.Item_Category_Id.Equals("")) { //如果是新建,并且没有传值给DisplayIndex,就取他所在子类里最大的displayindex+1 if (itemCategoryInfo.DisplayIndex == null || itemCategoryInfo.DisplayIndex == 0) { int displayindex = 0; //获取他的父类下的子分类的 IList <ItemCategoryInfo> list = GetItemCategoryListByParentId(itemCategoryInfo.Parent_Id).OrderByDescending(p => p.DisplayIndex).ToList(); if (list != null && list.Count() != 0) { int oldDisplayIndex = list[0].DisplayIndex == null?0: (int)list[0].DisplayIndex; displayindex = oldDisplayIndex + 1; } itemCategoryInfo.DisplayIndex = displayindex; } itemCategoryInfo.Item_Category_Id = NewGuid(); //2.提交用户信息 if (!SetItemCategoryTableInfo(loggingSessionInfo, itemCategoryInfo)) { strResult = "提交用户表失败"; return(strResult); } } else { CPOS.BS.DataAccess.ItemCategoryService server = new DataAccess.ItemCategoryService(loggingSessionInfo); strResult = server.SetItemCategoryInfoUpdate(itemCategoryInfo).ToString(); } var objectImagesBLL = new ObjectImagesBLL(loggingSessionInfo); var tmpImageList = objectImagesBLL.QueryByEntity(new ObjectImagesEntity() { ObjectId = itemCategoryInfo.Item_Category_Id }, null); if (tmpImageList != null && tmpImageList.Length > 0) { foreach (var tmpImageItem in tmpImageList) { objectImagesBLL.Delete(tmpImageItem); } } if (itemCategoryInfo.ImageUrl != null && itemCategoryInfo.ImageUrl.Length > 0) { objectImagesBLL.Create(new ObjectImagesEntity() { ImageId = NewGuid(), ObjectId = itemCategoryInfo.Item_Category_Id, ImageURL = itemCategoryInfo.ImageUrl }); } strResult = "保存成功!"; return(strResult); } catch (Exception ex) { throw (ex); } //return ""; }
//calculating segment area of 3 points static double Segment_Area_3_Points(IList <Point> points) { double segment_area = 0; for (int i = 0; i < points.Count(); i++) { for (int j = i + 1; j < points.Count(); j++) { var a = D(points[i].X, points[i].Y, points[j].X, points[j].Y); var mx = (points[i].X + points[j].X) / 2; var my = (points[i].Y + points[j].Y) / 2; Circle C, C2, C3; if (points[i].C1 == points[j].C1 || points[i].C1 == points[j].C2) { C = points[i].C1; } else //if (points[i].C2 == points[j].C1 || points[i].C2 == points[j].C2) { C = points[i].C2; } double a1 = C.a; double b1 = C.b; double r1 = C.r; var m = (b1 - my) / (a1 - mx); var n = -(mx * (b1 - my)) / (a1 - mx) + my; var sigma = r1 * r1 * (1 + m * m) - (b1 - m * a1 - n) * (b1 - m * a1 - n); var x1 = (a1 + b1 * m - m * n + Math.Sqrt(sigma)) / (1 + m * m); var x2 = (a1 + b1 * m - m * n - Math.Sqrt(sigma)) / (1 + m * m); var y1 = (n + a1 * m + b1 * m * m + m * Math.Sqrt(sigma)) / (1 + m * m); var y2 = (n + a1 * m + b1 * m * m - m * Math.Sqrt(sigma)) / (1 + m * m); if (points[i].C1 != C) { C2 = points[i].C1; } else { C2 = points[i].C2; } if (points[j].C1 != C) { C3 = points[j].C1; } else { C3 = points[j].C2; } var D2 = D(x1, y1, C2.a, C2.b); var D3 = D(x1, y1, C3.a, C3.b); double x, y; if (C2.r > D2 && C3.r > D3) { x = x1; y = y1; } else { x = x2; y = y2; } double theta; if (C.r > D(x, y, mx, my)) { theta = 2 * Math.Asin(a / (2 * r1)); } else { theta = 2 * (Math.PI - Math.Asin(a / (2 * r1))); } segment_area += (r1 * r1 / 2) * (theta - Math.Sin(theta)); //Console.WriteLine(segment_area); } } return(segment_area); }
public static bool JaFoiImportado(this IList <Classificacao> classificacoes, IList <Campeonato> campeonatos, IAssertionConcern assertionConcern) { return(!assertionConcern.IsSatisfiedBy( assertionConcern.AssertTrue(classificacoes?.Where(c => campeonatos.Any(cp => cp.Ano == c.Ano)).Count() == campeonatos?.Count(), "Dados já foram importados") )); }