public static void Main() { n = int.Parse(Console.ReadLine()); objects = new int[n]; arr = new int[n]; used = new bool[n]; values = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { objects[i] = int.Parse(Console.ReadLine()); } GenerateVariationsNoRepetitions(0); var minValues = values.Where(v => v.Value == values.Min(x => x.Value)); if (minValues.Count() == 1) { Console.WriteLine(minValues.FirstOrDefault().Key); } else { Console.WriteLine(minValues.OrderBy(x => x.Key).FirstOrDefault().Key); } }
public int Down(string tableName, string primaryColumn, Int64 primaryValue, string orderColumn, Int64 orderNumber) { var data = new Dictionary<string, Int64>(); using (DataCommand cmd = DataCommandManager.GetDataCommand("CommonDown")) { cmd.CommandText = string.Format(cmd.CommandText, tableName, primaryColumn, primaryValue, orderColumn,orderNumber); using (IDataReader dr = cmd.ExecuteDataReader()) { while (dr.Read()) { if (!Convert.IsDBNull(dr[primaryColumn]) && !Convert.IsDBNull(dr[orderColumn])) { data.Add(dr[primaryColumn].ToString(), Convert.ToInt64(dr[orderColumn])); } } } if (data.Count == 1) { return 2; } else { string sql = "update {0} set {1}={2} where {3}={4}"; StringBuilder sb = new StringBuilder(); foreach (KeyValuePair<string, long> keyValuePair in data) { if (keyValuePair.Key == primaryValue.ToString()) { sb.Append( string.Format( sql, tableName, orderColumn, data.Min(s => s.Value), primaryColumn, primaryValue) + ";"); } else { sb.Append( string.Format( sql, tableName, orderColumn, data.Max(s => s.Value), primaryColumn, keyValuePair.Key) + ";"); } } cmd.CommandText = sb.ToString(); return cmd.ExecuteNonQuery(); } } }
public static void SetChart(Dictionary<string, int> rawValues, Chart chart) { int fmin = 0; int fmax = 1; if (rawValues.Count > 0) { fmax = rawValues.Max(x => x.Value); fmin = rawValues.Min(x => x.Value); } //series init chart.Series.Clear(); // chart.Tag = values; var s = new Series(); s.ChartType = SeriesChartType.Bar; foreach (var kvp in rawValues) { s.Points.AddXY(kvp.Key, kvp.Value); var dpc = s.Points[s.Points.Count - 1]; dpc.Color = ColorExtras.GetRedGreenBlendedColour(kvp.Value, 0, fmax); dpc.ToolTip = kvp.Key + ":" + kvp.Value; } s.YAxisType = AxisType.Primary; s.XAxisType = AxisType.Secondary; s.IsVisibleInLegend = false; chart.Series.Add(s); //chartarea init chart.ChartAreas.Clear(); var ca = new ChartArea(); // ca.CursorX.IsUserEnabled = true; // ca.CursorX.IsUserSelectionEnabled = true; ca.AxisX2.ScrollBar.IsPositionedInside = false; ca.AxisX2.ScaleView.Size = zoomMax; ca.AxisX2.ScaleView.Position=rawValues.Count-ca.AxisX2.ScaleView.Size; ca.AxisX2.Interval = 1; ca.AxisY.Interval = MathExtras.Ceiling((Math.Abs(fmax) - Math.Abs(fmin)) / 8); if (ca.AxisY.Interval<1) ca.AxisY.Interval = 1; ca.AxisY.Minimum = fmin; ca.AxisY.Maximum = fmax; if (Math.Abs(ca.AxisY.Minimum - ca.AxisY.Maximum) < 1) ca.AxisY.Minimum--; s.Sort(PointSortOrder.Ascending); chart.ChartAreas.Add(ca); }
public void Save(Dictionary<string, List<News>> news) { decimal min = news.Min(n => n.Value.Min(m => m.RawScore)); decimal max = news.Max(n => n.Value.Max(m => m.RawScore)); using (var dbContext = new DistrictsInTownModelContainer()) { foreach (var district in news) AddArticlesToDB(dbContext, district, min, max); try { dbContext.SaveChanges(); } catch (Exception error) { Console.WriteLine(error.StackTrace); } Console.WriteLine("Total results: {0}", news.Sum(n => n.Value.Count)); } }
internal static Dictionary<DateTime, double> compute(Dictionary<DateTime, double> prices, int assetid) { bool accessbd = false; Dictionary<DateTime, double> returns = new Dictionary<DateTime, double>(); DateTime first = prices.Min(t=>t.Key); DateTime before; double price = 1; foreach (KeyValuePair<DateTime, double> kvp in prices) { if(kvp.Key != first){ before = kvp.Key.AddDays(-1); while (!prices.ContainsKey(before) && before >= first) before = before.AddDays(-1); if (!prices.ContainsKey(before) && before < first) { while (1 == 1) { try { price = AccessBD.Access.get_Price_Eur(assetid, before); accessbd = true; break; } catch (ArgumentException) { before = before.AddDays(-1); } } } if (accessbd == false) { price = prices[before]; } returns[kvp.Key] = Math.Log(prices[kvp.Key] / price); } } return returns; }
internal static Session GetUnassignedSessionWithFewestAvailableOptions(this IEnumerable<Assignment> assignments, IEnumerable<Session> sessions, SessionAvailabilityCollection sessionMatrix) { Session result = null; var assignedSessionIds = assignments.Where(a => a.SessionId != null).Select(a => a.SessionId); var sessionDictionary = new Dictionary<int, int>(); foreach (var session in sessions.Where(s => !assignedSessionIds.Contains(s.Id))) { sessionDictionary.Add(session.Id, sessionMatrix.GetAvailableAssignmentCount(session.Id)); } if (sessionDictionary.Count() > 0) { var min = sessionDictionary.Min(s => s.Value); var keys = sessionDictionary.Where(sd => sd.Value == min).Select(a => a.Key); result = sessions.Where(a => keys.Contains(a.Id)) .OrderByDescending(b => b.GetDependentDepth(sessions)) .ThenByDescending(c => c.GetDependentCount(sessions)) .FirstOrDefault(); } return result; }
internal void Fold(Dictionary<Int32,FoldRegion> regions) { if (regions.Count == 0) return; var start = regions.Min(rv => rv.Key); var end = regions.Max(rv => rv.Value.EndLine); var lc = @ref.Send(Sci.SCI_GETLINECOUNT); for (var i = start; i < end + 2; i++) { FoldRegion reg; if (regions.TryGetValue(i, out reg)) { //System.Diagnostics.Debug.WriteLine("sl=" + i + ";el=" + reg.EndLine + ";level=" + reg.Level); ProcessRegion(ref i, 0, regions, reg); i--; } else if (i < lc) @ref.Send(Sci.SCI_SETFOLDLEVEL, i, 0 | Sci.SC_FOLDLEVELBASE); } }
private Dictionary <string, double> CalculateMaxAndMinExchangeRate(Dictionary <DateTime, double> dates) { var dictionary = new Dictionary <string, double>(); var maxRate = dates.Max(x => x.Value); var minRate = dates.Min(x => x.Value); var matchesMax = dates.Where(pair => pair.Value == maxRate) .Select(pair => pair.Key).ToList(); var matchesMin = dates.Where(pair => pair.Value == minRate) .Select(pair => pair.Key).ToList(); var avarage = dates.Values.Average(); foreach (var min in matchesMin) { dictionary.Add(min.ToString("yyyy-MM-dd"), minRate); } foreach (var max in matchesMax) { dictionary.Add(max.ToString("yyyy-MM-dd"), maxRate); } dictionary.Add("avarage", avarage); return(dictionary); }
internal static Session GetUnassignedSessionWithFewestAvailableOptions(this IEnumerable <Assignment> assignments, IEnumerable <Session> sessions, SessionAvailabilityCollection sessionMatrix) { Session result = null; var assignedSessionIds = assignments.Where(a => a.SessionId != null).Select(a => a.SessionId); var sessionDictionary = new Dictionary <int, int>(); foreach (var session in sessions.Where(s => !assignedSessionIds.Contains(s.Id))) { sessionDictionary.Add(session.Id, sessionMatrix.GetAvailableAssignmentCount(session.Id)); } if (sessionDictionary.Count() > 0) { var min = sessionDictionary.Min(s => s.Value); var keys = sessionDictionary.Where(sd => sd.Value == min).Select(a => a.Key); result = sessions.Where(a => keys.Contains(a.Id)) .OrderByDescending(b => b.GetDependentDepth(sessions)) .ThenByDescending(c => c.GetDependentCount(sessions)) .FirstOrDefault(); } return(result); }
public override char FindFirstUniqueCharacter(string input) { // Keep this set as a ledger of all characters we see, giving us a O(1) check for duplicates via Contains HashSet <char> allCharacters = new HashSet <char>(); // First time we see a new char, store its value and index in this dictionary Dictionary <char, int> uniqueCharacters = new Dictionary <char, int>(); // Only loop once for (int i = 0; i < input.Length; i++) { char current = input[i]; // If we've seen this character before, then remove it from the uniques since it has a duplicate if (allCharacters.Contains(current)) { uniqueCharacters.Remove(current); } // Otherwise we have an undiscovered char, so record its index and add it to the ledger else { uniqueCharacters.Add(current, i); allCharacters.Add(current); } } char snowflake = '\0'; // If we have any unique characters, then find the one with the smallest index if (uniqueCharacters.Count > 0) { int index = uniqueCharacters.Min(entry => entry.Value); snowflake = input[index]; } return(snowflake); }
public static void Run() { string polymer = File.ReadAllText("input.txt"); var upperPolymer = polymer.ToUpper(); var distinctChars = upperPolymer.Distinct().ToArray(); Dictionary <char, int> results = new Dictionary <char, int>(); for (int i = 0; i < distinctChars.Length; i++) { string newPolymer = polymer.ToString(); newPolymer = newPolymer.Replace(distinctChars[i].ToString().ToUpper(), ""); newPolymer = newPolymer.Replace(distinctChars[i].ToString().ToLower(), ""); var polymerLength = React(newPolymer); results.Add(distinctChars[i], polymerLength); } var minPolymer = results.Min(kvp => kvp.Value); var keyChar = results.Where(kvp => kvp.Value == minPolymer).Select(kvp => kvp.Key.ToString()).First(); Console.WriteLine(""); Console.WriteLine($"{keyChar}={minPolymer}"); }
public void Extract(string rout) { try { Values.Clear(); Values = File.ReadLines(rout) .Skip(1) .Select(line => line.Split(';')) .ToDictionary(key => Convert.ToDouble(key[0]), value => Convert.ToDouble(value[1])); Values = Values .Where(v => v.Value != 0) .ToDictionary(k => k.Key, v => v.Value); minValue = Values.Min(v => v.Value); avgValue = Values.Average(v => v.Value); maxValue = Values.Max(v => v.Value); } catch (Exception e) { MessageBox.Show(e.Message, "Extract Values"); } }
public static List <KNNValuePair> KMeanGroup(MetricsEnum metricsEnum, int k) { List <KNNValuePair> distToMeans = new List <KNNValuePair>(); InverseCovarianceMatrix = null; var columns = GetColumnsWithoutLast(); string colName = "kmean_" + k + "_" + metricsEnum.ToString(); Dt.Columns.Add(colName); List <Dictionary <string, double> > tempMeans = new List <Dictionary <string, double> >(); //wybór losowych punktów (tymczasowe) for (int a = 0; a < k; a++) { DataRow randRow = Dt.NewRow(); var dict = new Dictionary <string, double>(); foreach (var column in columns) { var min = Dt .AsEnumerable() .Select(row => Convert.ToDouble(row[column])).ToList().Min(); var max = Dt .AsEnumerable() .Select(row => Convert.ToDouble(row[column])).ToList().Max(); Random rng = new Random(a); dict.Add(column, 0); var rngNumber = rng.NextDouble(); randRow[column] = rngNumber * (max - min) + min; } tempMeans.Add(dict); randRow[colName] = (a + 1); Dt.Rows.Add(randRow); } while (!CompareKMeans(tempMeans, k)) { distToMeans = new List <KNNValuePair>(); FillMeansTemp(tempMeans, k); //szacowanie nowej klasy for (int a = 0; a < Dt.Rows.Count - k; a++) { Dictionary <int, double> distances = new Dictionary <int, double>(); for (int b = Dt.Rows.Count - k; b < Dt.Rows.Count; b++) { distances.Add(b, CalculateMetrics(b, a, metricsEnum)); } var minMean = distances.Min(i => i.Value); var indexMean = distances.Where(i => i.Value == minMean).FirstOrDefault().Key; Dt.Rows[a][colName] = Dt.Rows[indexMean][colName]; distToMeans.Add(new KNNValuePair { Value = (string)Dt.Rows[indexMean][colName], Weight = minMean }); } //nowa średnia for (int b = Dt.Rows.Count - k; b < Dt.Rows.Count; b++) { foreach (var column in GetColumnsWithoutLast()) { var avg = Dt.Rows.Cast <DataRow>() .Take(Dt.Rows.Count - k) .Where(i => i[colName] == Dt.Rows[b][colName]); if (avg.Count() == 0) { Dt.Rows[b][column] = 0; } else { Dt.Rows[b][column] = avg .Select(row => Convert.ToDouble(row[column])) .Average(); } } } } //usuniecie zbędnych kolumn for (int a = 0; a < k; a++) { Dt.Rows.RemoveAt(Dt.Rows.Count - 1); } return(distToMeans); }
/// <summary> /// 获取候诊统计 /// 作者:郭明 /// 日期:2017年7月11日 /// </summary> /// <param name="request"></param> /// <returns></returns> public ResponseGetWaitStatisticsDTO GetWaitingStatistics(RequestGetWaitStatisticsDTO request) { //任务优先级 var TaskPriority = request.UserLevel; //处理一个任务需要消耗的时间(经验值) var TaskMinElapsedSeconds = 60 * 5; var result = new ResponseGetWaitStatisticsDTO() { ExpectedWaitTime = TaskMinElapsedSeconds }; var grabOPDService = new SysGrabService <string>("UserOPDRegister"); var today = DateTime.Now; int Year = today.Year; int Month = today.Month; int Day = today.Day; //查询指定医生需要等待的耗时 if (!string.IsNullOrEmpty(request.DoctorID)) { //通过数据库查询等待时间 //TODO:需要从任务列表中获取,任务列表需要支持现在的排序规则 var count = GetWaitingCount(request.DoctorID, request.ChannelID); result.ExpectedWaitTime = count * TaskMinElapsedSeconds; } else { //未领取的人数数量 long unTakeTaskCount = 0; //获取当前医生所在的分组(可能多个) var doctorGroups = GetDoctorGroupIdListByDoctorID(request.DoctorID); //邱所有分组下,相同优先级的任务总数 unTakeTaskCount = grabOPDService.TaskCount(TaskPriority, doctorGroups); var doctorTaskCountDict = new Dictionary <string, long>(); //查询当前组的医生 var doctorIdList = GetDoctorGroupMemberByUserLevel(request.UserLevel); //循环所有医生从任务列表中获取正在处理的订单数量 doctorIdList.ForEach(a => { var doingTaskCount = grabOPDService.DoingTaskCount(a); doctorTaskCountDict.Add(a, doingTaskCount); }); //医生数量 var doctorCount = doctorIdList.Count(); //医生最少的人数数量(这就能够知道最闲的是谁) var doctorMinTaskCount = doctorCount > 0 ? doctorTaskCountDict.Min(a => a.Value) : 0; //当前组总任务数/当前组成员数量 if (doctorCount > 0) { result.ExpectedWaitTime = ((unTakeTaskCount / doctorCount) + doctorMinTaskCount) * TaskMinElapsedSeconds; } else { result.ExpectedWaitTime = ((unTakeTaskCount) + doctorMinTaskCount) * TaskMinElapsedSeconds; } } return(result); }
private HashSet <Portal> GetPortals() { var minX = _map.Min(kvp => kvp.Key.X); var maxX = _map.Max(kvp => kvp.Key.X); var minY = _map.Min(kvp => kvp.Key.Y); var maxY = _map.Max(kvp => kvp.Key.Y); var portals = new HashSet <Portal>(); var textLocations = new HashSet <Point>(_map.Where(kvp => kvp.Value != '.').Select(kvp => kvp.Key)); while (textLocations.Count > 0) { var point = textLocations.First(); var adjacent = _allDirections .Select(d => new { Point = point.GetPoint(d), Direction = d }) .Where(a => _map.ContainsKey(a.Point) && _map[a.Point] != '.') .Select(a => new { a.Point, a.Direction, Type = _map[a.Point] }) .First(); textLocations.Remove(point); textLocations.Remove(adjacent.Point); var portalName = string.Empty; switch (adjacent.Direction) { case Direction.North: portalName = _map[adjacent.Point].ToString() + _map[point]; break; case Direction.South: portalName = _map[point].ToString() + _map[adjacent.Point]; break; case Direction.West: portalName = _map[adjacent.Point].ToString() + _map[point]; break; case Direction.East: portalName = _map[point].ToString() + _map[adjacent.Point]; break; default: throw new ArgumentOutOfRangeException(); } // The text is "normalized" (so we can find the accompanying portal). // What is the location of the portal? It depends on where the only adjacent '.' is to the portal. var pointAdjacentToMap = new[] { point, adjacent.Point } .SelectMany(p => _allDirections.Select(d => new { PortalPoint = p, MapPoint = p.GetPoint(d) })) .Where(a => _map.ContainsKey(a.MapPoint) && _map[a.MapPoint] == '.') .ToArray() .First(); var isOuter = pointAdjacentToMap.PortalPoint.X == minX + 1 || pointAdjacentToMap.PortalPoint.X == maxX - 1 || pointAdjacentToMap.PortalPoint.Y == minY + 1 || pointAdjacentToMap.PortalPoint.Y == maxY - 1; var portal = new Portal(portalName, pointAdjacentToMap.PortalPoint, pointAdjacentToMap.MapPoint, isOuter); portals.Add(portal); } return(portals); }
public static Dictionary <string, List <Iris> > KMean(Dictionary <int, Iris> DIris, Dictionary <string, List <double[]> > DAverage, ref double SSE) { // Penampung data sementara, dan buat clusternya kek di atas"nya Dictionary <string, List <Iris> > DCluster2 = new Dictionary <string, List <Iris> >(); DCluster2.Add("Iris-setosa", new List <Iris>()); DCluster2.Add("Iris-versicolor", new List <Iris>()); DCluster2.Add("Iris-virginica", new List <Iris>()); // ini cuma hitung similarity dari setiap data membernya foreach (Iris iris in DIris.Values) { Dictionary <string, double> DAvgSim = new Dictionary <string, double>(); // pertama DAverage dilooping dulu.... foreach (KeyValuePair <string, List <double[]> > cluster in DAverage) { // nanti kan Average di Index terakhir yang dihitung jadi itu yg dipake lahh // semoga kalian mengerti hikshiks... // kan ada banyak kek sy jelaskan tadi, kalo kalian betulan baca ini // jadi kita di sini cuma ambil average terbaru saja secara gampangnya dan yang terbaru itu // index terakhir int dex = cluster.Value.Count - 1; double sim_sp_length = Math.Pow(iris.sp_length - cluster.Value[dex][0], 2); double sim_sp_witdh = Math.Pow(iris.sp_width - cluster.Value[dex][1], 2); double sim_pt_length = Math.Pow(iris.pt_length - cluster.Value[dex][2], 2); double sim_pt_witdh = Math.Pow(iris.pt_width - cluster.Value[dex][3], 2); double sim = Math.Sqrt(sim_pt_length + sim_pt_witdh + sim_sp_length + sim_sp_witdh); DAvgSim.Add(cluster.Key, sim); } // ini berarti dia pertama di dulu nilai terkecil dari seluruh cluster yang ada (yang x=>x.Value..) // kemudian kita akan cari keynya dari value dari itu, karena nda bisa diambil langsung jadi begitu caranya double dist = DAvgSim.Min(x => x.Value); //if (dist == 0) //{ // Console.Write("la"); //} string kunci = DAvgSim.First(y => y.Value == dist).Key; SSE += dist * dist; // kan keynya berupa cluster, jadi dari cluster itu langsung kita input ke DCluster2(sudah di inisialisasi tadi) DCluster2[kunci].Add(iris); } num++; // menambah jumlah iterasi // Console.WriteLine("iterasi: " + num + ":" + SSE); Dictionary <string, double[]> DAvgGenerate = FindAverage(DCluster2); // cari rata" dari ini.... // Nahhh ini bagian yang paling susah kawan", nda usah dimengerti gpp rasanya karna nanti sy yg capek // saya jelaskan intinya dulu dahhh, begini nanti kita hitung semua rata" dari setiap cluster //(ituuu di atas DAvgGenerate), nanti kita bandingkan dengan semua data average sebelumnya... // kenapa kita harus bandingkan semua sebelumnya dan bukan yang terakhir saja?? karna nanti ada dia punya avg sekarang sama // dengan avg kedua sebelumnya, dan begitu berulang terus sampe infinite loop, jadi untuk jaga" sy pake // semuanya saja untuk disamakan averagenya, kalo berat baru saya batasi sampe 3 atau 4 average terbaru // ini menunjukkan kalo belum ada avg saat ini yang cocok dengan avg sebelumnya bool cocok = false; // pertama kita urutkan sesuai jumlah iterasi sekk, kita buat menurun karna kemungkinan avg itu sama // itu dari yang terbaru ke terlama // btw kalo kau bingung kenapa pake num, itu seperti jumlah dari List<double[]>.count di DCluster // btw lagi, jumlah itu list<double... blabla sama semua setiap cluster, kenapa bisa sama semua jumlahnya???? for (int i = num - 1; i >= 0; i--) { // nahh yg bool ini berbeda dengan bool di atas, ini seperti mengecek kalo seandainya avg nya sudah beda // artinya sudah nda mungkin sama sisanya, jadi kalo misalkan semua datanya sama kan jadi betul semua jadi bool nya true terus // pasti kau nda ngerti.. mending baca di baca nya dulu lahhh bool same = true; //ini hanya looping untuk setiap cluster yang tersedia foreach (string bunga in DAverage.Keys) { // kalo ini nanti di looping untuk setiap anggota dalam double[] itu tadi sebelumnya... // seperti yang sy bilang sebelumnya ini pasti 4 kali dilakukan karna isinya cuma 4 // ini dilakukan per cluster, bacaaaa cara kerja K-Meansss!!!! for (int j = 0; j < DAverage[bunga][i].Length; j++) { // ini untuk samakan apakah average dari cluster saat ini sama nda dengan DAverage(daftar //semua average) pada setiap bagian. kalo ada beda langsung bool same = false dan // nanti akan dilakukan cek lagi pada average yg lain if (DAverage[bunga][i][j].CompareTo(DAvgGenerate[bunga][j]) != 0) { same = false; } } } // kalo ini true berarti dia sudah menemukan pasangan sejatinya.... // maksudnya di sini semua averagenya sama pada setiap cluster dan setiap pembanding data member // pada clusternya dengan data sebelumnya jadi dihentikan saja // baru ganti bool cocok jadi true sebagai penanda sudah benar if (same) { cocok = true; break; } } // yaaah ini cuma tambahkan dia sebagai daftar DAverage baru sihh, nda ada modus lain foreach (string nama in DAvgGenerate.Keys) { DAverage[nama].Add(DAvgGenerate[nama]); } // ini seandainya dia masih jomblo, artinya dia harus cari lagi sampe dapat lahh // intinya dia ulang terus menerus lahh, dan semakin lama DAverage terisi dengan data sebelumnya // Sekarang saya tanya lagi kalo dia panggil methodnya sendiri apa namanya??? if (!cocok) { SSE = 0; DCluster2 = KMean(DIris, DAverage, ref SSE); } return(DCluster2); // kalo benar sudah dia kembalikan hasilnya yang benar setiap bunga berada di cluster apa }
public static Elevator Start(List <Elevator> elevatorList, int floor, int requestDirection) { List <int> elevatorFloors = new List <int>(); foreach (var elev in elevatorList) { elevatorFloors.Add(elev.Floor); } // Assess' which elevators are available to handle the request. List <Elevator> availableElevators = new List <Elevator>(); foreach (var elev in elevatorList) { var pse = elev.isPaused == false && elev.MaintenanceMode == false; var stationary = elev.stopQueue.Count == 0 && elev.direction == 0; if (pse && stationary) { availableElevators.Add(elev); // If it is stationary and is not paused or in maintenance mode it is available. } if (!pse && !stationary) { // If the elevator is going to pass the request floor it is available. if (elev.direction == 1 && elev.stopQueue.Min() > floor && requestDirection == elev.direction) { availableElevators.Add(elev); } else if (elev.direction == -1 && elev.stopQueue.Max() < floor && requestDirection == elev.direction) { availableElevators.Add(elev); } } } // Gets the distance between the available elevators and the request floor. foreach (var elev in availableElevators) { ElevatorDistances(elev, floor); } // Gets the closest elevator, and returns that elevator as a result. Elevator elevToSend = ClosestDistance(); return(elevToSend); // Get the distance between each elevator and the requested floor. void ElevatorDistances(Elevator elevator, int f) { ElevatorDistancesDict.Add(elevator, Math.Abs(elevator.Floor - f)); } // Select the closest elevator. Elevator ClosestDistance() { Elevator closestElev = ElevatorDistancesDict.Where(e => e.Value == ElevatorDistancesDict.Min(e2 => e2.Value)).First().Key; ElevatorDistancesDict.Clear(); return(closestElev); } }
public static int GetItemMinKeyLength <T>(this Dictionary <string, T> dict) { return((dict.Count != 0) ? dict.Min(p => p.Key.Length) : 0); }
public GCCollectionColumn(Dictionary<Benchmark, Stats> results, int generation) { ColumnName = $"Gen {generation}"; this.results = results; this.generation = generation; opsPerGCCount = results.Min(r => r.Value?.TotalOperations ?? 0); }
// Method to return purchase order details public Dictionary<string, object> GetOrderDetails() { // Insert regular and purchase price into cart for each item foreach (Dictionary<string, object> orderItem in this.OrderItems) { // Get records related to the item IEnumerable<DataRow> items = DBHelper.GetTable("Items").Table.AsEnumerable().Where( item => item["UPC"].ToString().Equals(orderItem["UPC"].ToString())); IEnumerable<DataRow> promotions = DBHelper.GetTable("Promotions").Table.AsEnumerable().Where( promotion => promotion["UPC"].ToString().Equals(orderItem["UPC"].ToString()) && ((DateTime)promotion["PromotionFrom"]).CompareTo(DateTime.Now) <= 0 && ((DateTime)promotion["PromotionTo"]).CompareTo(DateTime.Now) >= 0); // Get name of the item orderItem["ItemName"] = items.First()["ItemName"].ToString(); // Set regular price and purchase price double? regularPrice = null; double? memberPrice = null; double? promotionalPrice = null; // Regular price depends on if the customer is member if (this.OrderDetails["UserId"] != null) { regularPrice = double.Parse(items.First()["TenDaysPrice"].ToString()); } else { regularPrice = double.Parse(items.First()["RegularPrice"].ToString()); } // Get member price if (string.IsNullOrEmpty(items.First()["MemberPrice"].ToString())) { memberPrice = null; } else { memberPrice = double.Parse(items.First()["MemberPrice"].ToString()); } // Get promotional price if (promotions.Count() != 0) { promotionalPrice = double.Parse(items.First()["PromotionalPrice"].ToString()); } // Set regular price to item ordered orderItem["RegularPrice"] = regularPrice; Dictionary<string, double?> priceDictionary = new Dictionary<string, double?>(); priceDictionary.Add("RegularPrice", regularPrice); if (this.OrderDetails["UserId"] != null) { priceDictionary.Add("MemberPrice", memberPrice); } priceDictionary.Add("PromotionalPrice", promotionalPrice); // Set purchase price if (this.OrderDetails["UserId"] != null) { double? purchasePrice = priceDictionary.Min(pair => pair.Value); orderItem["PurchasePrice"] = purchasePrice; } else { double? purchasePrice = priceDictionary.Min(pair => pair.Value); orderItem["PurchasePrice"] = purchasePrice; } // If the cart belongs to member, save the price to database if (this.OrderDetails["UserId"] != null) { Dictionary<string, object> updatedRecord = new Dictionary<string, object>(); updatedRecord.Add("OrderId", orderItem["OrderId"]); updatedRecord.Add("UPC", orderItem["UPC"]); updatedRecord.Add("RegularPrice", orderItem["RegularPrice"]); updatedRecord.Add("PurchasePrice", orderItem["PurchasePrice"]); DBHelper.Update("OrderItems", updatedRecord); } } return this.OrderDetails; }
public void DictionaryExtensions_Min_ThrowsExceptionIfDictionaryIsEmpty() { var dictionary = new Dictionary<Int32, String>(); Assert.That(() => dictionary.Min(x => x.Key), Throws.TypeOf<InvalidOperationException>()); }
public void DictionaryExtensions_Min_ReturnsMinValue() { var dictionary = new Dictionary<Int32, String>() { { 4, "A" }, { 5, "B" }, { 6, "C" }, { 99, "D" }, { 10, "E" }, { 1, "F" }, { 12, "G" }, { 45, "H" }, }; var result = dictionary.Min(x => x.Key); TheResultingValue(result).ShouldBe(1); }
private Dictionary<string, double> computeNearestNeighbour(string targetUser) { Dictionary<string, double> nearestNeighbourDict = new Dictionary<string, double>(); foreach (var user in userDictionary) { if(!user.Key.Equals(targetUser)) { double similarity = similarityStrategy.computeSimilarity(userDictionary[targetUser].userPreferenceDictionary, userDictionary[user.Key].userPreferenceDictionary); int targetPreferenceCount = userDictionary[targetUser].userPreferenceDictionary.Count; int userPreferenceCount = userDictionary[user.Key].userPreferenceDictionary.Count; if (similarity > predefinedSimilarity && userPreferenceCount > targetPreferenceCount) { if(nearestNeighbourDict.Count < k) { nearestNeighbourDict.Add(user.Key, similarity); } else { // if list is full check for the minimum similarity and remove it, // to add the new user and update the predefinedSimilarity treshold. // http://stackoverflow.com/questions/23734686/c-sharp-dictionary-get-the-key-of-the-min-value var minUser = nearestNeighbourDict.Aggregate((x, y) => x.Value < y.Value ? x : y); if (similarity > minUser.Value) { nearestNeighbourDict.Remove(minUser.Key); nearestNeighbourDict.Add(user.Key, similarity); predefinedSimilarity = nearestNeighbourDict.Min(x => x.Value); } } } } } //create a new dictionary with the results sorted by descending. Dictionary<string, double> resultDictionary = new Dictionary<string, double>(); foreach(var keypair in nearestNeighbourDict.OrderByDescending(x => x.Value)) { resultDictionary.Add(keypair.Key, keypair.Value); } return resultDictionary; }
ArrayList DetectTileMove() { #region Detect Best Moves List<Transform> moves = new List<Transform>(); TakeMoves(ref moves, true); if (moves.Count == 0) { TakeMoves(ref moves); if (moves.Count == 0) { return null; } } moves = moves.Distinct().ToList(); float maxAsim = moves.Max(a => GetAsimilationCount(a.position)); moves = moves.Where(a => GetAsimilationCount(a.position) == maxAsim).ToList(); #endregion #region Create Dictionary Move/Unit Dictionary<Transform, Transform> targetTiles = new Dictionary<Transform, Transform>(); float nearUnitCost; foreach (var move in moves) { nearUnitCost = myUnits.Min(a =>Vector3.Distance(move.position, a.transform.parent.position)); Transform bestUnit=myUnits.First(a=>Vector3.Distance(a.transform.parent.position,move.position)==nearUnitCost).transform.parent; targetTiles.Add(move, bestUnit); } #endregion #region Best Unit/Best Move Transform resumeTarget=null; switch (level)//принятие решения соответственно уровню { case AiLevel.Easy:{ resumeTarget = targetTiles.FirstOrDefault(a=>Vector3.Distance(a.Key.position, a.Value.position)<1.6f).Key; if (resumeTarget == null) { resumeTarget = targetTiles.First().Key; } }break; case AiLevel.Middle: { nearUnitCost = targetTiles.Min(a => Vector3.Distance(a.Key.position, a.Value.position)); resumeTarget = targetTiles.First(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost).Key; } break; case AiLevel.Hard:{ nearUnitCost = targetTiles.Min(a => Vector3.Distance(a.Key.position, a.Value.position)); int minAroundUnit = targetTiles.Where(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost) .Min(a => AroundUnitCount(a.Value)); resumeTarget = targetTiles.First(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost && AroundUnitCount(a.Value) == minAroundUnit).Key; } break; } return new ArrayList(){targetTiles[resumeTarget], resumeTarget}; #endregion }
public void DictionaryExtensions_Min_ThrowsExceptionIfDictionaryIsEmpty() { var dictionary = new Dictionary<Int32, String>(); dictionary.Min(x => x.Key); }
private void btnUpdateEvironment_Click(object sender, EventArgs e) { DateTime minEnvironmentDT = dtEnvironmentBegin.MinDate; DateTime maxEnvironmentDT = dtEnvironmentBegin.MaxDate; if (dtEnvironmentBegin.Value >= dtEnvironmentEnd.Value) { MessageBoxEx.Show(this, "<font size='18'><b>Ngày bắt đầu phải trước ngày kết thúc !</b></font>", "<font size='15'><b>Thông báo</b></font>", MessageBoxButtons.OK, MessageBoxIcon.Warning); dtEnvironmentBegin.Value = minEnvironmentDT; dtEnvironmentEnd.Value = maxEnvironmentDT; } else { if (dtEnvironmentBegin.Value < minEnvironmentDT) { dtEnvironmentBegin.Value = minEnvironmentDT; } if (dtEnvironmentEnd.Value > maxEnvironmentDT) { dtEnvironmentEnd.Value = maxEnvironmentDT; } } DateTime beginTime = dtEnvironmentBegin.Value; DateTime endTime = dtEnvironmentEnd.Value; double sum = 0; int avgCount = 0; Dictionary<byte, List<double>> dictData_X = new Dictionary<byte, List<double>>(); Dictionary<byte, List<double>> dictData_Y = new Dictionary<byte, List<double>>(); foreach (LogRecord lrec in LogManager.LogEntryList) { ILogEnvironment rec = lrec as ILogEnvironment; if (rec != null) { if (rec.Time < beginTime || rec.Time > endTime) { continue; } sum += rec.Temperature; avgCount++; List<double> list_X; if (!dictData_X.TryGetValue(rec.ClientID, out list_X)) { list_X = new List<double>(); dictData_X.Add(rec.ClientID, list_X); } List<double> list_Y; if (!dictData_Y.TryGetValue(rec.ClientID, out list_Y)) { list_Y = new List<double>(); list_Y.Add(0); dictData_Y.Add(rec.ClientID, list_Y); } bool isSeparate = false; if (list_X.Count > 0 && (rec.Time - DateTime.FromOADate(list_X.Last())).TotalHours > 1) { isSeparate = true; } if (list_X.Count == 1) { list_X.Add(list_X.Last()); } if (isSeparate) { list_X.Add(list_X.Last()); list_X.Add(rec.Time.ToOADate()); } list_X.Add(rec.Time.ToOADate()); if (isSeparate) { list_Y.Add(0); list_Y.Add(-1); list_Y.Add(0); } if (rec.Temperature == 85) { if (list_Y.Count > 0) { list_Y.Add(list_Y.Last()); } else { list_Y.Add(30); } } else { list_Y.Add(rec.Temperature); } } } sum /= avgCount; txtAverageTemperature.Text = sum.ToString("n2") + "\u00B0C"; GraphPane pane = graphEnvironment.GraphPane; pane.Title.Text = "Lịch sử môi trường"; pane.YAxis.Title.Text = "Nhiệt độ (\u00B0C)"; pane.Fill = new Fill(Color.White, Color.LightGray, 45.0f); pane.XAxis.Type = AxisType.Date; pane.XAxis.Title.Text = "Thời gian"; pane.XAxis.Scale.Format = "HH:mm dd/MM/yy"; pane.XAxis.Scale.FontSpec.Size = 8; pane.CurveList.Clear(); foreach (KeyValuePair<byte, List<double>> data in dictData_X) { data.Value.Add(data.Value.Last()); dictData_Y[data.Key].Add(0); dictData_Y[data.Key].Add(-1); LineItem curve = pane.AddCurve("Nhiệt độ mạch " + data.Key + " (\u00B0C)", data.Value.ToArray(), filterSignal(dictData_Y[data.Key].ToArray(), 5, 0, 0), clientTemperatureColor[data.Key], SymbolType.None); } Graphics g = this.CreateGraphics(); pane.YAxis.ResetAutoScale(pane, g); pane.XAxis.ResetAutoScale(pane, g); g.Dispose(); pane.ZoomStack.Clear(); pane.XAxis.Scale.Format = "HH:mm dd/MM/yy"; pane.YAxis.Scale.Min = dictData_Y.Min(pair => pair.Value.FindAll(l => l > 0).Min()); pane.YAxis.Scale.Max = dictData_Y.Max(pair => pair.Value.FindAll(l => l > 0).Max()); graphEnvironment.AxisChange(); graphEnvironment.Refresh(); }
public Normalization(Dictionary <DateTime, double> dictionary) { Max = dictionary.Max(o => o.Value); Min = dictionary.Min(o => o.Value); }
static void Main(string[] args) { ////// Lambda expressions // Essentially a form of anonymous method. Can be type casted to Actions / Funcs Delagates // An anonymous method is a method that does not need to be defined and is typically disposed of once it has completed execution. // A lambda expression is a type of anonymous method that does not require the type to be explicitly defined // Lambda expressions are written as follows // (input-parameters) => expression // One or more inputs may be specified // The lambda declaration operator (=>) is what defines an operation as lambda // There are also lambda statements, which you can find examples of in the DataBuilder class as a part of the project. Lambda statements are unrelated to LINQ. // Lambda without a return - Action Delagate Action action = () => Console.WriteLine("Heres a test action"); action.Invoke(); // Lambda without a return and has an input - Action Delagate Action <string> writeMyLine = line => Console.WriteLine(line); writeMyLine.Invoke("some line"); // Lambda with a return type - Func Delagate Func <int, int> square = x => x * x; Console.WriteLine(square(5)); // 25 // Lambda with multiple inputs and a return type - Func Delagate Func <int, string, string> squareWithString = (toSquare, preamble) => preamble + (toSquare * toSquare).ToString(); Console.WriteLine(squareWithString(5, "The square of 5 is ")); // The square of 5 is 25 // For the purposes of LINQ, we will use lambda expressions to help us to manipulate data returned by LINQ methods. Most LINQ methods take an Action / Func as the method parameter // When using LINQ queries, the lambda is done in the background for you. LINQ stands for "Language - Integrated Query" /////// LINQ Queries // A LINQ Query consists of a few parts, take the follwing example // IEnumerable<T1> output = from RangeVariable<T2> in DataSource : IEnumerable<T2> // (data filtering / transformation ) // select RangeVariable<T1> // Step 1, specify the data source. In this case, myInts is the data source. // Only objects who inherit IEnumerable or IQueryable will be able to be a datasource in a LINQ query. // Step 2, Identify a range variable. In this case I used integer to describe the range variable // This is similar to how in a foreach loop, you specify the variable to be used in each iteration (int integer in myInts) but no type delcaration needs to occur // The type is inferred from the datasource (in this case List<int>) // Step 3, Filter / Sort / Order / Join / the range variable. This will filter and manipulate the data prior to output. This is not necessary to complete the query // Step 4, Produce the results of the query. Depending on the type of keyword used (select, group, ect) the result is returned based on the the type. // In the example below "select integer" returns IEnumerable<int> since integer is of type int. // However, if we changed the result to "select integer.ToString()" the return type would be of IEnumerable<string> // Best practices using LINQ include heavy usage of "var" to implicitly set the returns. Intellisense will let you know the type of the range variable, along with any other types // detailed within the query with a quick hover-over. If you do choose to explicitly define the type of return, Intellisense and the compiler will alert you to any errors List <int> myInts = new List <int> { 0, 3, 4, 12, 34, 156, 3, 34, 2, 34 }; // Type of IEnumerable<int> var integers = from integer in myInts select integer; var intList = integers.ToList(); /////// LINQ Methods // You can also use many of LINQs fuctionality in a more method based approach. The following example outputs the exact same data but written in another way. // In this way we are defining the data source as myInts and using the Select exension to select a sequence. // The Select() method takes a Func<int, TResult> as a parameter, given the data source of IEnumerable<int> // Using a lambda expression, the Func is defined as "integer => integer". This uses an <int> as the input variable and returns type <int>. // As above, this operation returns IEnumerable<int> but if we changed the lambda expression to integer => integer.ToString(), it would return IEnumerable<string>. var integersMethodBased = myInts.Select(integer => integer); var intMethodList = integersMethodBased.ToList(); // Why would we ever want to use LINQ? The tried and true way of forlooping over a collection, cleaning, filtering, sorting works just fine! // Some of the pros: // LINQ syntatically is not very complex, which enhances readiblilty of the code // For trivial transformations / filter / sort operations, LINQ requires far less code than tradition methods // LINQ can be used to query multiple data sources against each other easily // The compiler type checks the objects and syntax in the query (when interacting with a database a string for SQL does not) // IntelliSense support for all generic collections // Some of the downsides: // For really complex data manipulation, LINQ gets a little hairy // There is no step by step debugging LINQ Methods or Queries, which can make testing and exception hunting harder than it needs to be // Since all of the methods are extensions, anonymous, there is no code reuse (unless nested inside of a method). // LINQ is just another tool in the toolbox // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-linq-query-operations for more in depth documentation /////// EXAMPLES // Examples using Cars & Buyers found in DataBuilder DataBuilder dataBuilder = new DataBuilder(); // Randomly Generate X amount of Car objects of varying types dataBuilder.RandomlyGenerateCars(40); /////// A simple selection // Foreach Method - Non LINQ List <Car> theCarsForEach = new List <Car>(); foreach (Car car in dataBuilder.Cars) { theCarsForEach.Add(car); } // Linq Query Method IEnumerable <Car> theCarsQuery = from car in dataBuilder.Cars select car; // Linq Method Call // Lambda expression IEnumerable <Car> theCarsMethodCall = dataBuilder.Cars.Select(car => car); //List Conversions List <Car> theCarsQueryList = theCarsQuery.ToList(); List <Car> theCarsMethodCallList = theCarsMethodCall.ToList(); ////// Filtering dataBuilder.RandomlyAssignOwned(); // Foreach Method List <Car> theOwnedCarsForEach = new List <Car>(); foreach (Car car in dataBuilder.Cars) { if (car.Owned) { theOwnedCarsForEach.Add(car); } } // Query var theOwnedCarsQuery = from car in dataBuilder.Cars where car.Owned select car; // Method var theOwnedCarsMethod = dataBuilder.Cars.Where(car => car.Owned).Select(car => car).ToList(); //////// Multi level filtering // Foreach Method dataBuilder.RandomlyAssignMileage(); List <Car> theOwnedCarsAndMileageForEach = new List <Car>(); foreach (Car car in dataBuilder.Cars) { if (car.Owned && car.Mileage > 50000) { theOwnedCarsAndMileageForEach.Add(car); } } // Query var theOwnedCarsAndMileageQuery = from car in dataBuilder.Cars where car.Owned && car.Mileage > 50000 select car; // Method var theOwnedCarsAndMileageMethod = dataBuilder.Cars.Where(car => car.Owned && car.Mileage > 50000) .Select(car => car) .ToList(); //////// Ordering var orderedByMilageDesc = from car in dataBuilder.Cars orderby car.Mileage descending select car; var orderbyMilageMethod = dataBuilder.Cars.OrderByDescending(car => car.Mileage); //////// Grouping // Group by Make var groupByMake = from car in dataBuilder.Cars group car by car.Make; foreach (IGrouping <string, Car> group in groupByMake) { Console.WriteLine($"There are {group.Count()} {group.Key}s"); } // Method Calls var groupByMakeMethod = dataBuilder.Cars.GroupBy(car => car.Make); // Group by object type var groupByType = from car in dataBuilder.Cars group car by car.GetType(); // Method Calls var groupByTypeMethod = dataBuilder.Cars.GroupBy(car => car.GetType()); foreach (IGrouping <Type, Car> group in groupByType) { Console.WriteLine($"This group contains {group.Count()} {group.Key}s"); } // Transforming objects IEnumerable <SportsCar> findSportsCars = from car in dataBuilder.Cars where car.GetType() == typeof(SportsCar) select car as SportsCar; Console.WriteLine(findSportsCars.FirstOrDefault().Rev()); // Method Calls and ForEach // One of the most useful ways of using LINQ is to use the ForEach exension to preform generic transformations instead of breaking things out to a new block that will be used once. // Here's a few examples List <int> someInts = new List <int>(); myInts.ForEach(theInt => someInts.Add(theInt)); // Call methods on collections dataBuilder.Cars.ForEach(car => car.Describe()); // Assign large amounts of data dataBuilder.Cars.ForEach(car => car.Owned = false); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); // Call methods on selections of collections dataBuilder.Cars.Where(car => car.Doors > 2) .ToList() // returns IEnumerable and in order to access .ForEach the type must be list .ForEach(biggerCar => biggerCar.Describe()); // Navigating dictionaries var exampleDictionary = new Dictionary <int, string> { { 1, "one" }, { 2, "two" }, { 3, "three" }, { 15998946, "Fifteen million, nine hundred ninety eight thousand, nine hundred and fourty six" } }; // Maths int sumOfLengthsGreaterThanTwo = exampleDictionary.Where(kvp => kvp.Key > 2).Sum(kvp => kvp.Value.Length); double averageGreaterThanOrEqualToThree = exampleDictionary.Keys.Where(intKey => intKey >= 3).Average(intKey => intKey); int maxNumber = exampleDictionary.Keys.Max(numbers => numbers); int shortestText = exampleDictionary.Min(text => text.Value.Length); /////// Joins /// Joins allow the developer to take 2 (or more) different objects and join them together into a mixed collection as long as the join occurs on an accessible type for both objects /// and both properties types implement IEquatable /// In the following examples, strings are equality compared against each other to make the join occur /// The return type of 'select new { Property = value, ...}' is an anonymous type. These types do not require a definition (like anonymous methods) and allow for easy /// One time use data wrangling when combining multiple classes dataBuilder.RandomlyAssignOwned(); /// This exmaple matches each buyer to their favorite cars /// Returns anonymous IEnumerable<'a(Buyer, IEnumerable<Car>)> var buyersToCars = from buyer in dataBuilder.Buyers join car in dataBuilder.Cars on buyer.PreferredMake equals car.Make into favoriteCars select new { Buyer = buyer, Cars = favoriteCars }; /// Which of these is easier to read??? buyersToCars.ToList().ForEach(buyerCarGroup => buyerCarGroup.Cars.ToList() .ForEach(car => Console.WriteLine($"{buyerCarGroup.Buyer.FirstName} {buyerCarGroup.Buyer.LastName} who likes {buyerCarGroup.Buyer.PreferredMake} matches with " + $"a {car.ModelRelease.Year} {car.Make} {car.Model} with {car.Mileage} miles"))); foreach (var CarBuyerGroup in buyersToCars) { Console.WriteLine($"\nBuyer: {CarBuyerGroup.Buyer.FirstName} {CarBuyerGroup.Buyer.LastName} likes {CarBuyerGroup.Buyer.PreferredMake}"); foreach (var car in CarBuyerGroup.Cars) { car.Describe(); } } //////// Sub queries with join operation, anonymous types output /// Lets pretend that we are a car dealership with the collection in DataBuilder containing cars we have in our database for all vehicles bought and sold. /// In the preceding example, we had potential buyers who didn't have car insurance and we paired them with cars that were already owned; not an ideal representation of what we could sell /// In this next example, we can filter out buyers to who are eligible and match them with cars they can actually own, ordered by least mileage to most, giving a more personalized marketing stragegy var goodBuyersToUnownedCars = from buyer in dataBuilder.Buyers where buyer.HasCarInsurance join car in dataBuilder.Cars on buyer.PreferredMake equals car.Make into favoriteCars select new { GoodBuyer = buyer, ProspectiveCars = from favoriteCar in favoriteCars where !favoriteCar.Owned orderby favoriteCar.Mileage ascending select favoriteCar }; foreach (var BuyerCarCombo in goodBuyersToUnownedCars) { Console.WriteLine($"\nQualified Buyer {BuyerCarCombo.GoodBuyer.FirstName} {BuyerCarCombo.GoodBuyer.LastName}"); if (BuyerCarCombo.ProspectiveCars.ToList().Count > 0) { foreach (var car in BuyerCarCombo.ProspectiveCars) { car.Describe(); } } else { Console.WriteLine($"There are no {BuyerCarCombo.GoodBuyer.PreferredMake} cars for sale!"); } } Console.ReadLine(); }
public static void normalize_graph(Dictionary<EntityLink,double> graph) { // Scales the edge weights so that the lightest is about 0.0 and the // heaviest is about 1.0, to within floating point errors. List<EntityLink> graph_keys = new List<EntityLink> (graph.Keys); // remove a constant offset from each edge double lightest_link = graph.Min(g => g.Value); for (int i = 0; i < graph_keys.Count; i++) { graph [graph_keys [i]] -= lightest_link; } // now scale everyone double heaviest_link = graph.Max(g => g.Value); for (int i = 0; i < graph_keys.Count; i++) { graph [graph_keys [i]] /= heaviest_link; } }
public void KMean() { // K = 2 random //var p1 = dataSet.Where(x => x.Id == 1).Single(); //Ditances(p1, dataSet).ToList(); //Console.WriteLine("============================="); //var p4 = dataSet.Where(x => x.Id == 4).Single(); //Ditances(p4, dataSet).ToList(); var dicOfAverage = new Dictionary <Subject, double>(); foreach (var center in dataSet) { var average = Distance(center, dataSet).Average(x => x.Item1); dicOfAverage.Add(center, average); Console.WriteLine("Cen: {0} = {1}", center.Id, average); } // select p7 center var minDisP = dicOfAverage .Where(y => y.Value == dicOfAverage.Min(x => x.Value)).First(); //dataSet.Remove(p7); var group1 = new List <Subject>(); foreach (var dis in Distance(minDisP.Key, dataSet)) { Console.WriteLine("p: {0}, d: {1}", dis.Item2.Id, dis.Item1); if (dis.Item1 <= minDisP.Value) { group1.Add(dis.Item2); } } group1.Add(minDisP.Key); foreach (var item in group1) { Console.WriteLine("p: {0}", item.Id); } //----------------------------------------------------------------- var remainData = dataSet.Where(x => !group1.Contains(x)).ToList(); if (remainData.Count() > 0) { Console.WriteLine("-----------------------------------------------------------------"); dicOfAverage = new Dictionary <Subject, double>(); foreach (var center in remainData) { var average = Distance(center, remainData).Average(x => x.Item1); dicOfAverage.Add(center, average); Console.WriteLine("Cen: {0} = {1}", center.Id, average); } minDisP = dicOfAverage.Where(y => y.Value == dicOfAverage.Min(x => x.Value)).First(); var group2 = new List <Subject>(); foreach (var dis in Distance(minDisP.Key, remainData)) { Console.WriteLine("p: {0}, d: {1}", dis.Item2.Id, dis.Item1); if (dis.Item1 <= minDisP.Value) { group2.Add(dis.Item2); } } group2.Add(minDisP.Key); foreach (var item in group2) { Console.WriteLine("p: {0}", item.Id); } remainData = remainData.Where(x => !group2.Contains(x)).ToList(); } }
public Dictionary<Difficulty, Song> readChart(string directory) { //read file var files = (string[]) Directory.GetFiles(directory); var stream = files.FirstOrDefault(c => (c.ToLower().Contains(".sm")) && !c.ToLower().Contains(".old") && !c.ToLower().Contains(".dwi") && !c.Contains("._")); if(stream == null) stream = files.FirstOrDefault(c => (c.ToLower().Contains(".dwi")) && !c.ToLower().Contains(".old") && !c.Contains("._")); if(stream == null) return null; StreamReader sr = new StreamReader(stream); songContent = sr.ReadToEnd(); sr.Close(); //split all line and put on a list var thesong = songContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); List<string> listLine = new List<string>(); listLine.AddRange(thesong); List<int> indexNotes = new List<int>(); //traitement des commentaires. /* Non : Impossible de savoir si single ou double :( for(int i=0; i < listLine.Count;i++){ if(listLine.ElementAt(i).Contains("//")){ listLine[i] = listLine.ElementAt(i).Split("//".ToCharArray())[0]; } }*/ for(int i=0; i < listLine.Count;i++){ if(listLine.ElementAt(i).Contains("NOTES")){ indexNotes.Add(i); } } Dictionary<Difficulty, Song> outputSongs = new Dictionary<Difficulty, Song> (); try{ //get generic information var thetitle = listLine.FirstOrDefault(c => c.Contains("TITLE")).Split(':'); var title = thetitle[1].Replace(";",""); var thesubtitle = listLine.FirstOrDefault(c => c.Contains("SUBTITLE")).Split(':'); var subtitle = thesubtitle[1].Replace(";",""); var theartist = listLine.FirstOrDefault(c => c.Contains("ARTIST")).Split(':'); var artist = theartist[1].Replace(";",""); var theoffset = listLine.FirstOrDefault(c => c.Contains("OFFSET")).Split(':'); if(theoffset[1].Contains("//")) theoffset[1] = theoffset[1].Split('/')[0]; //Special Destination fix var offset = System.Convert.ToDouble(theoffset[1].Replace(";","")); var thesamplestart = listLine.FirstOrDefault(c => c.Contains("SAMPLESTART")).Split(':'); var samplestart = System.Convert.ToDouble(thesamplestart[1].Replace(";","")); var thesamplelenght = listLine.FirstOrDefault(c => c.Contains("SAMPLELENGTH")).Split(':'); var samplelenght = System.Convert.ToDouble(thesamplelenght[1].Replace(";","")); //"file://" + var theBanner = listLine.FirstOrDefault(c => c.Contains("BANNER")).Split(':'); var bannerTemp = ""; if(!String.IsNullOrEmpty(theBanner[1].Replace(";",""))) { bannerTemp = files.FirstOrDefault(c => c.Contains(theBanner[1].Replace(";",""))); }else{ bannerTemp = files.FirstOrDefault(c => (c.ToLower().Contains("bn") || c.ToLower().Contains("banner")) && (c.ToLower().Contains(".png") || c.ToLower().Contains(".jpg") || c.ToLower().Contains(".bmp") || c.ToLower().Contains(".jpeg"))); } var banner = "noBanner"; if(!String.IsNullOrEmpty(bannerTemp)){ banner = "file://" + bannerTemp.Replace('\\', '/'); } var theBpmListMesured = new Dictionary<double, double>(); var theStopListMesured = new Dictionary<double, double>(); var theBpmList = new Dictionary<double, double>(); var theStopList = new Dictionary<double, double>(); var theBpmMesureList = new List<double>(); var theStopMesureList = new List<double>(); //getting bpms with mesure string[] thebpm = listLine.FirstOrDefault(c => c.Contains("BPMS")).Split(':'); string thebpmline = thebpm[1]; string[] splitbpm = thebpmline.Split(','); /*double previousbps = 0; double previoustime = 0; double previousmesure = 0; List<double> timeToMesureBPM = new List<double>();*/ foreach(string s in splitbpm){ string[] mysplit = s.Replace(";","").Split('='); if(!theBpmListMesured.ContainsKey(System.Convert.ToDouble(mysplit[0]))) theBpmListMesured.Add(System.Convert.ToDouble(mysplit[0]), System.Convert.ToDouble(mysplit[1])); //theBpmList.Add(previousbps == 0 ? 0 : previoustime + (System.Convert.ToDouble(mysplit[0]) - previousmesure)/previousbps, System.Convert.ToDouble(mysplit[1])); /*previousbps = System.Convert.ToDouble(mysplit[1])/(double)60.0; previoustime = theBpmList.Last().Key; previousmesure = System.Convert.ToDouble(mysplit[0]); timeToMesureBPM.Add(System.Convert.ToDouble(mysplit[0])); Debug.Log ("bpm : " + theBpmList.Last().Key);*/ } //getting stops mesured int stopbegin = listLine.IndexOf(listLine.FirstOrDefault(c => c.Contains("STOPS"))); string thestop = ""; bool stopTheRool = false; if(!listLine.ElementAt(stopbegin).Contains("STOPS:;")){ for(int i=stopbegin; !stopTheRool; i++){ if( listLine.ElementAt(i).Contains("//")){ thestop += listLine.ElementAt(i).Split('/')[0]; }else{ thestop += listLine.ElementAt(i); } if(listLine.ElementAt(i).Contains(";")) stopTheRool = true; } thestop = thestop.Replace("/n", ""); thestop = thestop.Replace(";", ""); } if(thestop != ""){ string[] thestopsplit = thestop.Split(':'); string thestopline = thestopsplit[1]; string[] splitstop = thestopline.Split(','); /*previousbps = theBpmList.First().Value; previoustime = 0; previousmesure = 0;*/ foreach(string s in splitstop){ var mysplit = s.Split('='); theStopListMesured.Add(System.Convert.ToDouble(mysplit[0]), System.Convert.ToDouble(mysplit[1])); /* var theMesure = timeToMesureBPM.IndexOf(timeToMesureBPM.FirstOrDefault(d => d == timeToMesureBPM.Where(c => c <= System.Convert.ToDouble(mysplit[0])).Max())); previousbps = System.Convert.ToDouble(theBpmList.ElementAt(theMesure).Value)/(double)60.0; previoustime = theBpmList.ElementAt(theMesure).Key; previousmesure = timeToMesureBPM.ElementAt(theMesure); theStopList.Add(previoustime + ((System.Convert.ToDouble(mysplit[0])) - previousmesure)/previousbps, System.Convert.ToDouble(mysplit[1])); Debug.Log("real mesure : " + (System.Convert.ToDouble(mysplit[0])) + " analyse : " + theStopList.Last().Key + " : " + theStopList.Last().Value + " : " + theMesure + " previous time : " + previoustime + " previous mesure : " + previousmesure + " previous bps " + previousbps + " (" + previousbps*60.0 + ") bpm");*/ } } //change bpm and stops mesured by time //Bug encore. double previousbps = 0; double stoptime = 0; double previoustime = 0; double previousmesure = 0; while(theStopListMesured.Count != 0 && theBpmListMesured.Count != 0){ if((theStopListMesured.First().Key < theBpmListMesured.First().Key)){ theStopList.Add(previoustime + stoptime + (theStopListMesured.First().Key - previousmesure)/previousbps, theStopListMesured.First().Value); theStopMesureList.Add(theStopListMesured.First().Key); previoustime += (theStopListMesured.First().Key - previousmesure)/previousbps; previousmesure = theStopListMesured.First().Key; stoptime += theStopListMesured.First().Value; theStopListMesured.Remove(theStopListMesured.First().Key); }else if((theStopListMesured.First().Key > theBpmListMesured.First().Key)){ theBpmList.Add(previousbps == 0 ? 0 : previoustime + stoptime + (theBpmListMesured.First().Key - previousmesure)/previousbps, theBpmListMesured.First().Value); theBpmMesureList.Add(theBpmListMesured.First().Key); previoustime += (previousbps == 0 ? 0 : (theBpmListMesured.First().Key - previousmesure)/previousbps); previousbps = theBpmList.Last().Value/(double)60.0; previousmesure = theBpmListMesured.First().Key; theBpmListMesured.Remove(theBpmListMesured.First().Key); }else if(theStopListMesured.First().Key == theBpmListMesured.First().Key){ theStopList.Add(previousbps == 0 ? 0 : previoustime + stoptime + (theStopListMesured.First().Key - previousmesure)/previousbps, theStopListMesured.First().Value); theStopMesureList.Add(theStopListMesured.First().Key); theBpmList.Add(previousbps == 0 ? 0 : previoustime + stoptime + (theBpmListMesured.First().Key - previousmesure)/previousbps, theBpmListMesured.First().Value); theBpmMesureList.Add(theBpmListMesured.First().Key); previoustime += (previousbps == 0 ? 0 : (theBpmListMesured.First().Key - previousmesure)/previousbps); previousbps = theBpmList.Last().Value/(double)60.0; previousmesure = theBpmListMesured.First().Key; stoptime += theStopListMesured.First().Value; theStopListMesured.Remove(theStopListMesured.First().Key); theBpmListMesured.Remove(theBpmListMesured.First().Key); } } while(theStopListMesured.Count != 0){ theStopList.Add(previoustime + stoptime + (theStopListMesured.First().Key - previousmesure)/previousbps, theStopListMesured.First().Value); theStopMesureList.Add(theStopListMesured.First().Key); previoustime += (theStopListMesured.First().Key - previousmesure)/previousbps; previousmesure = theStopListMesured.First().Key; stoptime += theStopListMesured.First().Value; theStopListMesured.Remove(theStopListMesured.First().Key); } while(theBpmListMesured.Count != 0){ theBpmList.Add(previousbps == 0 ? 0 : previoustime + stoptime + (theBpmListMesured.First().Key - previousmesure)/previousbps, theBpmListMesured.First().Value); theBpmMesureList.Add(theBpmListMesured.First().Key); previoustime += (previousbps == 0 ? 0 : (theBpmListMesured.First().Key - previousmesure)/previousbps); previousbps = theBpmList.Last().Value/(double)60.0; previousmesure = theBpmListMesured.First().Key; theBpmListMesured.Remove(theBpmListMesured.First().Key); } var thedisplayBPM = ""; if(listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")) != null){ try{ string[] thes = listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")).Split(':'); if(thes.Count() > 2){ thedisplayBPM = System.Convert.ToDouble(thes[1].Replace(";", "")).ToString("0") + " -> " + System.Convert.ToDouble(thes[2].Replace(";", "")).ToString("0"); }else{ thedisplayBPM = System.Convert.ToDouble(thes[1].Replace(";", "")).ToString("0"); } }catch{ //Special Gravity Blast fix string[] thes = listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")).Split(':'); var theindex = 0; for(int o=0; o<thes.Count(); o++){ if(thes[o].Contains("DISPLAYBPM")){ theindex = o + 1; } } if((thes.Count() - theindex - 1) > 2){ thedisplayBPM = System.Convert.ToDouble(thes[theindex].Replace(";", "")).ToString("0") + " -> " + System.Convert.ToDouble(thes[theindex+1].Replace(";", "")).ToString("0"); }else{ thedisplayBPM = System.Convert.ToDouble(thes[theindex].Replace(";", "")).ToString("0"); } } }else{ var themin = theBpmList.Min(c => c.Value); var themax = theBpmList.Max(c => c.Value); if(themin == themax){ thedisplayBPM = themax.ToString("0"); }else{ thedisplayBPM = themin.ToString("0") + " -> " + themax.ToString("0"); } } //debug /*foreach(var el in theStopList){ Debug.Log(el.Key); }*/ //For all difficulties foreach(int index in indexNotes){ var theNewsong = new Song(); //easy variable getted theNewsong.title = title; theNewsong.subtitle = subtitle; theNewsong.artist = artist; theNewsong.banner = banner; theNewsong.offset = offset; theNewsong.samplestart = samplestart; theNewsong.samplelenght = samplelenght; theNewsong.bpms = theBpmList; theNewsong.stops = theStopList; theNewsong.mesureBPMS = theBpmMesureList; theNewsong.mesureSTOPS = theStopMesureList; theNewsong.bpmToDisplay = thedisplayBPM; /*if(files.FirstOrDefault(c => c.Contains(".ogg")) == null){ foreach(var fil in files){ Debug.Log(fil); } }*/ theNewsong.song = "file://" + files.FirstOrDefault(c => c.Contains(".ogg") || c.Contains(".OGG")).Replace('\\', '/'); //getting song information int beginInformation = index; string dl = ""; var theinfo = listLine.ElementAt(beginInformation + 1).Replace(":","").Trim(); if(theinfo.Contains("double")){ dl = "D"; }else if(!theinfo.Contains("single") || theinfo.Contains("pump") || theinfo.Contains("ez2") || theinfo.Contains("para") || theinfo.Contains("ds3ddx") || theinfo.Contains("pnm") || theinfo.Contains("bm") || theinfo.Contains("maniax") || theinfo.Contains("techno")){ dl = "STOP"; } theNewsong.stepartist = listLine.ElementAt(beginInformation + 2).Replace(":","").Trim(); theNewsong.setDifficulty(dl + listLine.ElementAt(beginInformation + 3).Replace(":","").Trim()); theNewsong.level = System.Convert.ToInt32(listLine.ElementAt(beginInformation + 4).Replace(":","").Trim()); //getting stepchart int beginstepchart = beginInformation+6; while(listLine.ElementAt(beginstepchart).Contains("//") || String.IsNullOrEmpty(listLine.ElementAt(beginstepchart).Trim()) || listLine.ElementAt(beginstepchart) == ""){ if(listLine.ElementAt(beginstepchart).Contains("NOTES")) dl = "STOP"; beginstepchart++; } if(listLine.ElementAt(beginstepchart).Contains("NOTES")) dl = "STOP"; //if(theNewsong.title == "The Last Kiss") Debug.Log(listLine.ElementAt(beginstepchart)); if(dl != "STOP"){ var numberOfSteps = 0; var numberOfMines = 0; var numberOfRoll = 0; var numberOfFreezes = 0; var numberOfJump = 0; var numberOfStepsWJ = 0; theNewsong.stepchart.Add(new List<string>()); for(int i = beginstepchart; !listLine.ElementAt(i).Contains(";"); i++){ if(listLine.ElementAt(i).Contains(",")){ theNewsong.stepchart.Add(new List<string>()); }else if(!String.IsNullOrEmpty(listLine.ElementAt(i))){ theNewsong.stepchart.Last().Add(listLine.ElementAt(i)); numberOfSteps += listLine.ElementAt(i).Count(c => c == '1'); numberOfSteps += listLine.ElementAt(i).Count(c => c == '2'); numberOfSteps += listLine.ElementAt(i).Count(c => c == '4'); numberOfFreezes += listLine.ElementAt(i).Count(c => c == '2'); numberOfRoll += listLine.ElementAt(i).Count(c => c == '4'); numberOfMines += listLine.ElementAt(i).Count(c => c == 'M'); numberOfStepsWJ += listLine.ElementAt(i).Count(c => c == '1'); numberOfStepsWJ += listLine.ElementAt(i).Count(c => c == '2'); numberOfStepsWJ += listLine.ElementAt(i).Count(c => c == '4'); var countmesure = listLine.ElementAt(i).Count(c => c == '1') + listLine.ElementAt(i).Count(c => c == '2') + listLine.ElementAt(i).Count(c => c == '4'); if(countmesure == 2){ numberOfStepsWJ -= countmesure; numberOfJump++; } if(countmesure >= 3){ numberOfStepsWJ -= countmesure; } } } theNewsong.numberOfSteps = numberOfSteps; theNewsong.numberOfFreezes = numberOfFreezes; theNewsong.numberOfRolls = numberOfRoll; theNewsong.numberOfMines = numberOfMines; theNewsong.numberOfJumps = numberOfJump; theNewsong.numberOfStepsWithoutJumps = numberOfStepsWJ; //A faire le mode double ! if(dl == "") fakeCreation(theNewsong); //A mettre //if(outputSongs.ContainsKey(theNewsong.difficulty)) theNewsong.sip = new SongInfoProfil(theNewsong.title, theNewsong.subtitle, theNewsong.numberOfSteps, theNewsong.difficulty, theNewsong.level); outputSongs.Add(theNewsong.difficulty, theNewsong); } } }catch(Exception e){ Debug.Log(directory + " // " + e.Message + " //st : " + e.StackTrace); } return outputSongs; }
public void CalculateSegmentWidth(Bitmap bitmap, double sensitivity) { int Height = bitmap.Height; int Width = bitmap.Width; var results = new Dictionary<int, double>(); for (int i = 0; i < Width - 1; i++) { var l = new List<Color>(); var r = new List<Color>(); for (int j = 0; j < Height; j++) { l.Add(bitmap.GetPixel(i, j)); r.Add(bitmap.GetPixel(i + 1, j)); } results.Add(i, EdgeCompareScore(l, r)); if (SegmentWidthCalculated != null && i % 20 == 0) SegmentWidthCalculated(null, new EventArgs()); } double max = results.Max(x => x.Value); double min = results.Min(x => x.Value); double range = max - min; Dictionary<int, double> normalisedResults = results.ToDictionary(x => x.Key, x => (x.Value - min) / range); List<int> edgeIndexes = normalisedResults.Where(x => x.Value > sensitivity).Select(x => x.Key).ToList(); IEnumerable<int> columnWidth = edgeIndexes.Where((x, idx) => idx < edgeIndexes.Count - 1 && idx >= 0).Select( (x, idx) => Math.Abs(edgeIndexes[idx] - edgeIndexes[idx + 1])); var groupedColumnWidth = columnWidth.GroupBy(i => i).Select(g => new { g.Key, Count = g.Count() }); SegmentWidth = groupedColumnWidth.Where(x => x.Count == groupedColumnWidth.Max(y => y.Count)).Select(x => x.Key).First(); if (SegmentWidthCalculationCompleted != null) SegmentWidthCalculationCompleted(null, new EventArgs()); }
/// <summary> /// The actual scheduling procedure /// </summary> private void Runner() { var scheduled = new Dictionary<long, DateTime>(); while (!m_terminate) { //TODO: As this is executed repeatedly we should cache it // to avoid frequent db lookups //Determine schedule list var lst = Program.DataConnection.Schedules; foreach(var sc in lst) { if (!string.IsNullOrEmpty(sc.Repeat)) { DateTime start; DateTime last = new DateTime(0, DateTimeKind.Utc); if (!scheduled.TryGetValue(sc.ID, out start)) { start = new DateTime(sc.Time.Ticks, DateTimeKind.Utc); last = sc.LastRun; } try { start = GetNextValidTime(start, last, sc.Repeat, sc.AllowedDays); } catch (Exception ex) { Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex); } //If time is exceeded, run it now if (start <= DateTime.UtcNow) { var jobsToRun = new List<Server.Runner.IRunnerData>(); //TODO: Cache this to avoid frequent lookups foreach(var id in Program.DataConnection.GetBackupIDsForTags(sc.Tags).Distinct().Select(x => x.ToString())) { //See if it is already queued var tmplst = from n in m_worker.CurrentTasks where n.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup select n.Backup; var tastTemp = m_worker.CurrentTask; if (tastTemp != null && tastTemp.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup) tmplst.Union(new [] { tastTemp.Backup }); //If it is not already in queue, put it there if (!tmplst.Any(x => x.ID == id)) { var entry = Program.DataConnection.GetBackup(id); if (entry != null) jobsToRun.Add(Server.Runner.CreateTask(Duplicati.Server.Serialization.DuplicatiOperation.Backup, entry)); } } //Caluclate next time, by adding the interval to the start until we have // passed the current date and time //TODO: Make this more efficient int i = 50000; while (start <= DateTime.UtcNow && i-- > 0) try { start = GetNextValidTime(start, start.AddSeconds(1), sc.Repeat, sc.AllowedDays); } catch(Exception ex) { Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex); continue; } Server.Runner.IRunnerData lastJob = jobsToRun.LastOrDefault(); if (lastJob != null && lastJob != null) lock(m_lock) m_updateTasks[lastJob] = new Tuple<ISchedule, DateTime, DateTime>(sc, start, DateTime.UtcNow); foreach(var job in jobsToRun) m_worker.AddTask(job); if (start < DateTime.UtcNow) { //TODO: Report this somehow continue; } } scheduled[sc.ID] = start; } } var existing = lst.ToDictionary(x => x.ID); Server.Serialization.Interface.ISchedule sc_tmp = null; //Sort them, lock as we assign the m_schedule variable lock(m_lock) m_schedule = (from n in scheduled where existing.TryGetValue(n.Key, out sc_tmp) orderby n.Value select existing[n.Key]).ToArray(); // Remove unused entries foreach(var c in (from n in scheduled where !existing.ContainsKey(n.Key) select n.Key).ToArray()) scheduled.Remove(c); //Raise event if needed if (NewSchedule != null) NewSchedule(this, null); int waittime = 0; //Figure out a sensible amount of time to sleep the thread if (scheduled.Count > 0) { //When is the next run scheduled? TimeSpan nextrun = scheduled.Min((x) => x.Value) - DateTime.UtcNow; if (nextrun.TotalMilliseconds < 0) continue; //Don't sleep for more than 5 minutes waittime = (int)Math.Min(nextrun.TotalMilliseconds, 60 * 1000 * 5); } else { //No tasks, check back later waittime = 60 * 1000; } //Waiting on the event, enables a wakeup call from termination // never use waittime = 0 m_event.WaitOne(Math.Max(100, waittime), false); } }
private void OnGUI() { if (uiFocusPath == null) { return; } //提取所有焦点 uiFocusToLocaionDic = uiFocusPath.NewUIFocusArray.Where(temp => temp != null).ToDictionary(temp => temp, temp => temp.transform.position); EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("缩放比例:", GUILayout.Width(50)); scale = GUILayout.HorizontalSlider(scale, 0.2f, 5f, GUILayout.Width(100)); EditorGUILayout.LabelField("显示全部", GUILayout.Width(50)); showAll = EditorGUILayout.Toggle(showAll, GUILayout.Width(15)); EditorGUILayout.LabelField("点击选择对象", GUILayout.Width(75)); clickButtonToSelect = EditorGUILayout.Toggle(clickButtonToSelect, GUILayout.Width(15)); EditorGUILayout.EndHorizontal(); if (uiFocusToLocaionDic.Count <= 0) { EditorGUILayout.EndVertical(); return; } //计算出一个范围 float minX = uiFocusToLocaionDic.Min(temp => temp.Value.x) - 30; float minY = uiFocusToLocaionDic.Min(temp => temp.Value.y) - 30; float maxX = uiFocusToLocaionDic.Max(temp => temp.Value.x) + 30; float maxY = uiFocusToLocaionDic.Max(temp => temp.Value.y) + 30; Vector2 baseOffset = new Vector2(minX, minY); //基础的偏差值 Vector2 baseSize = new Vector2(maxX - minX, maxY - minY); //基础的大小 Rect baseRect = new Rect(baseOffset, baseSize); //基础的位置 Dictionary <UIFocus, Rect> uiFocusToShowRectDic = new Dictionary <UIFocus, Rect>(); //本次运行时的显示区域 scroll = GUI.BeginScrollView(new Rect(0, 40, position.width, position.height - 40), scroll, new Rect(0, 0, baseRect.width * scale, baseRect.height * scale)); foreach (KeyValuePair <UIFocus, Vector3> item in uiFocusToLocaionDic)//遍历绘制 { Vector2 nowPos = item.Value; nowPos = nowPos - baseOffset; nowPos.y = baseSize.y - nowPos.y; nowPos *= scale; Rect tempRect = new Rect(nowPos.x, nowPos.y, 70, 15); GUIStyle buttonStyle = buttonNotSelectStyle; if (selectUIFcous == item.Key) { buttonStyle = buttonSelectStyle; } if (GUI.Button(tempRect, item.Key.name, buttonStyle)) { selectUIFcous = item.Key; if (clickButtonToSelect) { Selection.activeGameObject = selectUIFcous.gameObject; } } uiFocusToShowRectDic.Add(item.Key, new Rect(nowPos.x - scroll.x, nowPos.y + 40 - scroll.y, 70, 15)); } GUI.EndScrollView(); EditorGUILayout.EndVertical(); Dictionary <Vector3[], UIFocus[]> lineToFocusDic = new Dictionary <Vector3[], UIFocus[]>();//线对应焦点字典 //绘制线 Action <Vector3, Vector3, UIFocus, UIFocus> DrawLineAction = (startVec, endVec, startFocus, endFocus) => { Handles.color = Color.red; Handles.DrawLine(startVec, endVec); lineToFocusDic.Add(new Vector3[] { startVec, endVec }, new UIFocus[] { startFocus, endFocus }); }; foreach (UIFocusPath.FocusRelaship item in uiFocusPath.UIFocusArrayRelaships) { if (showAll || item.This == selectUIFcous) { if (!uiFocusToShowRectDic.ContainsKey(item.This)) { continue; } Rect thisRect = uiFocusToShowRectDic[item.This]; if (item.Up) { Vector3 thisVec = new Vector3(thisRect.xMin + thisRect.width / 2, thisRect.yMin); if (uiFocusToShowRectDic.ContainsKey(item.Up)) { Rect upRect = uiFocusToShowRectDic[item.Up]; Vector3 target = upRect.center; DrawLineAction(thisVec, target, item.This, item.Up); } } if (item.Down) { Vector3 thisVec = new Vector3(thisRect.xMin + thisRect.width / 2, thisRect.yMax); if (uiFocusToShowRectDic.ContainsKey(item.Down)) { Rect downRect = uiFocusToShowRectDic[item.Down]; Vector3 target = downRect.center; DrawLineAction(thisVec, target, item.This, item.Down); } } if (item.Left) { Vector3 thisVec = new Vector3(thisRect.xMin, thisRect.yMin + thisRect.height / 2); if (uiFocusToShowRectDic.ContainsKey(item.Left)) { Rect leftRect = uiFocusToShowRectDic[item.Left]; Vector3 target = leftRect.center; DrawLineAction(thisVec, target, item.This, item.Left); } } if (item.Right) { Vector3 thisVec = new Vector3(thisRect.xMax, thisRect.yMin + thisRect.height / 2); if (uiFocusToShowRectDic.ContainsKey(item.Right)) { Rect rightRect = uiFocusToShowRectDic[item.Right]; Vector3 target = rightRect.center; DrawLineAction(thisVec, target, item.This, item.Right); } } } } Event e = Event.current; //绘制选择对象的四个游标 if (selectUIFcous) { Rect thisRect = uiFocusToShowRectDic[selectUIFcous]; Rect upRect = new Rect(thisRect.xMin + thisRect.width / 2 - 5, thisRect.yMin - 10, 10, 10); Rect downRect = new Rect(thisRect.xMin + thisRect.width / 2 - 5, thisRect.yMax, 10, 10); Rect leftRect = new Rect(thisRect.xMin - 10, thisRect.yMin + thisRect.height / 2 - 5, 10, 10); Rect rightRect = new Rect(thisRect.xMax, thisRect.yMin + thisRect.height / 2 - 5, 10, 10); GUI.DrawTexture(upRect, relashipButtonTexture); GUI.DrawTexture(downRect, relashipButtonTexture); GUI.DrawTexture(leftRect, relashipButtonTexture); GUI.DrawTexture(rightRect, relashipButtonTexture); if (e.button == 1 && e.rawType == EventType.mouseDown) { if (upRect.Contains(e.mousePosition)) { forwardType = EnumEditorGUIFocusPathForward.Up; } else if (downRect.Contains(e.mousePosition)) { forwardType = EnumEditorGUIFocusPathForward.Down; } else if (leftRect.Contains(e.mousePosition)) { forwardType = EnumEditorGUIFocusPathForward.Left; } else if (rightRect.Contains(e.mousePosition)) { forwardType = EnumEditorGUIFocusPathForward.Right; } } } if (e.button == 1) { if (forwardType != null) { if (selectUIFcous) { Rect thisRect = uiFocusToShowRectDic[selectUIFcous]; Rect upRect = new Rect(thisRect.xMin + thisRect.width / 2 - 5, thisRect.yMin - 10, 10, 10); Rect downRect = new Rect(thisRect.xMin + thisRect.width / 2 - 5, thisRect.yMax, 10, 10); Rect leftRect = new Rect(thisRect.xMin - 10, thisRect.yMin + thisRect.height / 2 - 5, 10, 10); Rect rightRect = new Rect(thisRect.xMax, thisRect.yMin + thisRect.height / 2 - 5, 10, 10); Handles.color = Color.gray; switch (forwardType.Value) { case EnumEditorGUIFocusPathForward.Left: Handles.DrawLine(leftRect.center, e.mousePosition); break; case EnumEditorGUIFocusPathForward.Right: Handles.DrawLine(rightRect.center, e.mousePosition); break; case EnumEditorGUIFocusPathForward.Up: Handles.DrawLine(upRect.center, e.mousePosition); break; case EnumEditorGUIFocusPathForward.Down: Handles.DrawLine(downRect.center, e.mousePosition); break; } } } } if (e.button == 1 && e.rawType == EventType.mouseUp) { if (forwardType != null) { KeyValuePair <UIFocus, Rect>[] mouseUpResultArray = uiFocusToShowRectDic.Where(temp => temp.Value.Contains(e.mousePosition)).ToArray(); KeyValuePair <UIFocus, Rect> mouseUpResult = mouseUpResultArray.FirstOrDefault(); UIFocusPath.FocusRelaship focusRelaship = uiFocusPath.UIFocusArrayRelaships.FirstOrDefault(temp => temp.This == selectUIFcous); if (focusRelaship != null) { switch (forwardType.Value) { case EnumEditorGUIFocusPathForward.Left: focusRelaship.Left = mouseUpResult.Key; break; case EnumEditorGUIFocusPathForward.Right: focusRelaship.Right = mouseUpResult.Key; break; case EnumEditorGUIFocusPathForward.Up: focusRelaship.Up = mouseUpResult.Key; break; case EnumEditorGUIFocusPathForward.Down: focusRelaship.Down = mouseUpResult.Key; break; } } forwardType = null; } } }
public uint GetHeaderColumnPosition(WorksheetEntry worksheet, Dictionary<string, uint> sectionLines, string columnName) { var rowLine = sectionLines.Min(spp => spp.Value) - 1; var headerSectionLine = _spreadsheetFacade.GetCellsValues(worksheet, rowLine, rowLine, 1, uint.MaxValue).ToList(); return headerSectionLine.Where(h => h.Value.Equals(columnName)).Select(h => h.Column).First(); }
private void PerformTeachingSerie(int wantedNoOfNodes, int changesPerPatch, int patchesPerTeachingSerie) { // patch --> its error change - lower = better Dictionary<NetworkPatch, double> patchesEfficiency = new Dictionary<NetworkPatch, double>(); double serieStartError = network_.CalculateTrainingSqrError(); int startNetworkHash = network_.GetHashCode(); while (patchesEfficiency.Count < patchesPerTeachingSerie) { #if DEBUG string graphBeforePatch = network_.PrintNetworkStruct(); #endif NetworkPatch patch = patchFactory_.CreateAndApplyPatch(changesPerPatch, wantedNoOfNodes); patchesEfficiency[patch] = network_.CalculateTrainingSqrError() - serieStartError; #if DEBUG string graphAfterPatch = network_.PrintNetworkStruct(); #endif patch.Revert(); #if DEBUG string graphAfterRevert = network_.PrintNetworkStruct(); double errorAfterNotApplyingPatch = network_.CalculateTrainingSqrError(); if (serieStartError != errorAfterNotApplyingPatch) { Logger.Log(this, String.Format( "REVERT WENT WRONG!\n" + "<<<<<<<<<<<<GRAPH BEFORE PATCH >>>>>>>>>>\n{0}\n" + "<<<<<<<<<<<<GRAPH AFTER PATCH >>>>>>>>>>\n{1}\n" + "<<<<<<<<<<<<GRAPH AFTER REVERT >>>>>>>>>>\n{2}\n", graphBeforePatch, graphAfterPatch, graphAfterRevert), 10); throw new ApplicationException("revert went wrong"); } #endif } //NOTE: what is interesting double.NaN is lowest possible number AND double.NaN != double.NaN //WTF?? double bestChange = patchesEfficiency.Min(x => double.IsNaN(x.Value) ? double.PositiveInfinity : x.Value); Logger.Log(this, String.Format("best change {0}", bestChange)); if (bestChange <= 0.0d && //IMPORTANT: for now only !double.IsInfinity(bestChange) && !double.IsNaN(bestChange)) { Logger.Log(this, "applying patch!"); NetworkPatch bestPatch = patchesEfficiency.First(patch => patch.Value == bestChange).Key; bestPatch.Apply(); double errorAfterApplyingPatch = network_.CalculateTrainingSqrError(); Logger.Log(this, String.Format("error after appplying patch {0}", errorAfterApplyingPatch)); //#if DEBUG if (bestChange < -1E-2) { PrintGraphVisualization(network_); } //#endif double delta = 1E-4; if (serieStartError + bestChange - errorAfterApplyingPatch > delta) throw new ApplicationException("something went rly bad"); } else { Logger.Log(this, "NOT applying patch"); } }
public async Task <int[]> GetCells(IRandomAccessStream imageStream, int cellsCount) { int[] cells = new int[cellsCount]; int[] cellValues = new int[cellsCount]; Dictionary <Point, Color> pixels = new Dictionary <Point, Color>(); WriteableBitmap bitmap = await BitmapFactory.New(trainSetConfig.ImageWidth, trainSetConfig.ImageHeight).FromStream(imageStream); for (int i = 0; i < bitmap.PixelWidth; i++) { for (int j = 0; j < bitmap.PixelHeight; j++) { var color = bitmap.GetPixel(i, j); if (color.A == 255 && color.R == 0 && color.G == 0 && color.B == 0) //if (color.A == 255 && color.R != 255 && color.G != 255 && color.B != 255) { pixels.Add(new Point(i, j), color); } } } Debug.WriteLine(pixels.Count, "Black pixels in image"); if (pixels.Count == 0) { return(null); } var leftTop = new Point(pixels.Min(p => p.Key.X), pixels.Min(p => p.Key.Y)); var rightBottom = new Point(pixels.Max(p => p.Key.X), pixels.Max(p => p.Key.Y)); var boundBitmapWidth = (int)(rightBottom.X - leftTop.X + 1); var boundBitmapHeight = (int)(rightBottom.Y - leftTop.Y + 1); WriteableBitmap boundBitmap = new WriteableBitmap(boundBitmapWidth, boundBitmapHeight); WhiteBitmap(boundBitmap); foreach (var pixel in pixels) { int x = (int)(pixel.Key.X - leftTop.X); int y = (int)(pixel.Key.Y - leftTop.Y); Color color = pixel.Value; boundBitmap.SetPixel(x, y, color); } //await SaveBitmapToFile(boundBitmap, (int)(rightBottom.X - leftTop.X + 1), (int)(rightBottom.Y - leftTop.Y + 1), "boundBitmap"); int stretchedSize = 100; var stretchedBitmap = boundBitmap.Resize(stretchedSize, stretchedSize, WriteableBitmapExtensions.Interpolation.Bilinear); //await SaveBitmapToFile(stretchedBitmap, stretchedSize, stretchedSize, "stretchedBitmap"); for (int i = 0; i < stretchedBitmap.PixelWidth; i++) { for (int j = 0; j < stretchedBitmap.PixelHeight; j++) { var color = stretchedBitmap.GetPixel(i, j); if (color.A == 255 && color.R == 0 && color.G == 0 && color.B == 0) { cellValues[i / SPLIT_VALUE * trainSetConfig.ImageWidth + j / SPLIT_VALUE]++; } } } for (int i = 0; i < cellsCount; i++) { if (cellValues[i] > SPLIT_VALUE) { cells[i] = 1; } } Debug.WriteLine(cells.Count(x => x == 1), "Count of 1 in cells array"); return(cells); }
/// <summary> /// Predicts the specified BMP. /// </summary> /// <param name="bmp">The image in bitmap format.</param> /// <param name="topK">The top k accurate result to return.</param> /// <returns></returns> public List <PredResult> Predict(Bitmap bmp, int topK = 3) { try { Variable inputVar = modelFunc.Arguments[0]; NDShape inputShape = inputVar.Shape; int imageWidth = inputShape[0]; int imageHeight = inputShape[1]; var resized = bmp.Resize(imageWidth, imageHeight, true); List <float> resizedCHW = resized.ParallelExtractCHW(); // Create input data map var inputDataMap = new Dictionary <Variable, Value>(); var inputVal = Value.CreateBatch(inputShape, resizedCHW, GlobalParameters.Device); inputDataMap.Add(inputVar, inputVal); inputVar = modelFunc.Arguments[1]; //inputDataMap.Add(inputVar, null); Variable outputVar = modelFunc.Outputs.Where(x => (x.Shape.TotalSize == 1000)).ToList()[0]; // Create output data map. Using null as Value to indicate using system allocated memory. // Alternatively, create a Value object and add it to the data map. var outputDataMap = new Dictionary <Variable, Value>(); outputDataMap.Add(outputVar, null); // Start evaluation on the device modelFunc.Evaluate(inputDataMap, outputDataMap, GlobalParameters.Device); // Get evaluate result as dense output var outputVal = outputDataMap[outputVar]; var outputData = outputVal.GetDenseData <float>(outputVar); Dictionary <int, float> outputPred = new Dictionary <int, float>(); for (int i = 0; i < outputData[0].Count; i++) { outputPred.Add(i, outputData[0][i]); } var topList = outputPred.OrderByDescending(x => (x.Value)).Take(topK).ToList(); List <PredResult> result = new List <PredResult>(); float sumpredresult = outputPred.Sum(x => (x.Value)); float avgpredresult = outputPred.Average(x => (x.Value)); float min = outputPred.Min(x => (x.Value)); float max = outputPred.Max(x => (x.Value)); foreach (var item in topList) { result.Add(new PredResult() { Score = item.Value, Name = actualValues[item.Key] }); } Logging.WriteTrace("Prediction Completed"); return(result); } catch (Exception ex) { Logging.WriteTrace(ex); throw ex; } }
private string GetItem(string documentName, int nextPrevCount, string documentPath, int currentId = 0) { var localPath = ExtentionHelpers.ExchangSlash(documentPath + "/" + documentName); var filePaths = Directory.GetFiles(localPath); var dictionary = new Dictionary<int, string>(); foreach (var item in filePaths) { if (Path.GetExtension(item).ToUpper() == ApplicationConfiguration.ImageExtension.ToUpper()) { var id = GetIds(item); dictionary.Add(id, GetPath(item)); } } var max = dictionary.Max(x => x.Key); var min = dictionary.Min(x => x.Key); var incrementCount = (nextPrevCount >= 1) ? 1 : -1; currentId = (nextPrevCount >= 1 && max == currentId) ? 0 : currentId; currentId = (nextPrevCount < 1 && min == currentId) ? max + 1 : currentId; var data = dictionary.FirstOrDefault(x => x.Key == currentId + incrementCount); return data.Value; }
private static DateTime GetNextTime_(byte timerType, int delayPeriod, byte delayUnit, byte runOn, DateTime runAt, byte runType, DateTime runOnDate, DateTime startDate, DateTime endDate, string runOnDay, string daysOfWeek, DateTime previousActionTime) { DateTime date = previousActionTime; if (timerType == (byte)TimerType.TimeDelay) { switch ((DateInterval)delayUnit) { case DateInterval.Years: date = date.AddYears(delayPeriod); break; case DateInterval.Months: date = date.AddMonths(delayPeriod); break; case DateInterval.Weeks: date = date.AddDays(delayPeriod * 7); break; case DateInterval.Days: date = date.AddDays(delayPeriod); break; case DateInterval.Minutes: date = date.AddMinutes(delayPeriod); break; case DateInterval.Seconds: date = date.AddSeconds(delayPeriod); break; case DateInterval.Hours: default: date = date.AddHours(delayPeriod); break; } if (runOn == (byte)RunOn.Weekday) { date = date.AddDays(DaysToWeekday(date.DayOfWeek)); } return(RunAt(runAt, date)); } else if (timerType == (byte)TimerType.Date) { if (runType == (byte)RunType.OnADate) { runOnDate = RunAt(runAt, runOnDate); if (runOnDate < date) { return(date); } else if (runOnDate > date) { return(runOnDate); } } else { if ((endDate < date) || (date > startDate && date < endDate) || date < startDate) { return(date); } } } else if (timerType == (byte)TimerType.Week) { var runOnDays = new List <int>(); if (!string.IsNullOrWhiteSpace(daysOfWeek)) { var daysList = daysOfWeek.Split(','); foreach (var item in daysList) { var value = default(int); if (int.TryParse(item, out value)) { runOnDays.Add(value); } } } if (runOnDays.Any(d => d == (int)date.DayOfWeek)) { return(date); } else { IDictionary <DayOfWeek, int> days = new Dictionary <DayOfWeek, int>(); foreach (DayOfWeek day in runOnDays) { int daysUntilDayOfWeek = ((int)day - (int)date.DayOfWeek + 7) % 7; days.Add(day, daysUntilDayOfWeek); } var minDays = days.Min(d => d.Value); date.AddDays(minDays); return(date); } } return(date); }
private int GetMinTourForTourType(Dictionary <int, TourNode> tourDef) { return(tourDef.Min(td => td.Value.TourId)); }
public static void Run() { var lines = File.ReadAllLines(@"Day17\Input.txt"); Dictionary <Point, SquareType> map = new Dictionary <Point, SquareType>(); foreach (var line in lines) { var lineResult = ParseLine(line); for (int x = lineResult.xFrom; x <= lineResult.xTo; x++) { for (int y = lineResult.yFrom; y <= lineResult.yTo; y++) { map[new Point(x, y)] = SquareType.Clay; } } (int xFrom, int xTo, int yFrom, int yTo) ParseLine(string lineToParse) { var split = lineToParse.Split(','); split = split.Select(xx => xx.Trim()).OrderBy(xx => xx[0]).ToArray(); var x = split[0].Trim().Split('=')[1].Trim(); var xFrom = int.Parse(x.Split('.').First()); var xTo = int.Parse(x.Split('.').Last()); var y = split[1].Trim().Split('=')[1].Trim(); var yFrom = int.Parse(y.Split('.').First()); var yTo = int.Parse(y.Split('.').Last()); return(xFrom, xTo, yFrom, yTo); } } int yMax = map.Max(x => x.Key.Y); int yMin = map.Min(x => x.Key.Y); int xMax = map.Max(x => x.Key.X) + 1; int xMin = map.Min(x => x.Key.X) - 1; map[new Point(500, 1)] = SquareType.WaterFlowing; var pointsToProcess = GetPossiblyAffectedCells(new Point(500, 1)).ToList(); while (true) { var newnewFlowingPoints = new List <Point>(); foreach (var newPOint in pointsToProcess) { var squareMeter = GetValue(newPOint.X, newPOint.Y); if (squareMeter != SquareType.WaterFlowing) { continue; } var keyX = newPOint.X; var keyY = newPOint.Y; if (keyY == yMax) { continue; } var under = GetValue(keyX, keyY + 1); var left = keyX == xMin ? SquareType.Border : GetValue(keyX - 1, keyY); var right = keyX == xMax ? SquareType.Border : GetValue(keyX + 1, keyY); if (under == SquareType.WaterFlowing) { continue; } if (under == SquareType.Sand) { var point = new Point(keyX, keyY + 1); map[point] = SquareType.WaterFlowing; newnewFlowingPoints.AddRange(GetPossiblyAffectedCells(point)); } else { if (left == SquareType.Sand) { var point = new Point(keyX - 1, keyY); map[point] = SquareType.WaterFlowing; newnewFlowingPoints.AddRange(GetPossiblyAffectedCells(point)); } if (right == SquareType.Sand) { var point = new Point(keyX + 1, keyY); map[point] = SquareType.WaterFlowing; newnewFlowingPoints.AddRange(GetPossiblyAffectedCells(point)); } } if (under == SquareType.Clay || under == SquareType.WaterStill) { int xLeftNew = keyX; while (xLeftNew > xMin && GetValue(xLeftNew, keyY) == SquareType.WaterFlowing) { xLeftNew--; } int xRightNew = keyX; while (xRightNew < xMax && GetValue(xRightNew, keyY) == SquareType.WaterFlowing) { xRightNew++; } var ll = GetValue(xLeftNew, keyY); var rr = GetValue(xRightNew, keyY); if (ll == SquareType.Clay && rr == SquareType.Clay) { for (int j = xLeftNew + 1; j < xRightNew; j++) { map[new Point(j, keyY)] = SquareType.WaterStill; newnewFlowingPoints.AddRange(GetPossiblyAffectedCells(new Point(j, keyY))); } } } } pointsToProcess = newnewFlowingPoints; if (pointsToProcess.Count == 0) { break; } } SquareType GetValue(int x, int y) { return(map.GetValueOrDefault(new Point(x, y), SquareType.Sand)); } IEnumerable <Point> GetPossiblyAffectedCells(Point affectedPoint) { yield return(new Point(affectedPoint.X - 1, affectedPoint.Y)); yield return(new Point(affectedPoint.X + 1, affectedPoint.Y)); yield return(new Point(affectedPoint.X, affectedPoint.Y - 1)); yield return(new Point(affectedPoint.X, affectedPoint.Y + 1)); yield return(affectedPoint); } // Draw(); Console.WriteLine(map.Count(x => x.Key.Y >= yMin && (x.Value == SquareType.WaterStill))); void Draw() { using (StreamWriter s = new StreamWriter(new FileStream("result.txt", FileMode.OpenOrCreate))) { for (int y = 0; y <= yMax; y++) { for (int x = xMin; x <= xMax; x++) { s.Write(map.GetValueOrDefault(new Point(x, y), SquareType.Sand).Draw()); } s.WriteLine(); } } } }
/// <summary>Obtain volume and frequency from the referenced AudioSource.</summary> /// <param name="audioSource">The AudioSource to analyse.</param> /// <param name="filter">The pitch-frequency dictionary to use as a filter.</param> /// <param name="samples">The array of samples to write into.</param> /// <param name="spectrum">The spectrum array to write into.</param> /// <param name="hzValue">The frequency output.</param> public static void AnalyseSound(AudioSource audioSource, Dictionary <string, int> filter, out float[] samples, out float[] spectrum, out int hzValue) { samples = new float[ProgramManager.SAMPLE_SIZE]; spectrum = new float[ProgramManager.SAMPLE_SIZE]; // Obtains the audio spectrum data. audioSource.GetSpectrumData(spectrum, 0, FFTWindow.BlackmanHarris); float highestSample = 0; float sampleIndex = 0; int lowestIndex = (int)System.Math.Round(ProgramManager.SAMPLE_SIZE * (float)filter.Min(x => x.Value) / (float)(ProgramManager.SAMPLE_RATE * 0.5045f)); int highestIndex = (int)System.Math.Round(ProgramManager.SAMPLE_SIZE * (float)filter.Max(x => x.Value) / (float)(ProgramManager.SAMPLE_RATE * 0.5045f)); // Locates the highest sample in the array of spectrums. for (int i = lowestIndex; i <= highestIndex; i++) { if (spectrum [i] > highestSample && spectrum [i] > ProgramManager.THRESHOLD) { highestSample = spectrum [i]; sampleIndex = (float)i; } } // Convert sample index to frequency. hzValue = (int)(sampleIndex * (ProgramManager.SAMPLE_RATE * 0.5045f) / ProgramManager.SAMPLE_SIZE); }
public static DateTime?GetLastFetchUtc() { return(forecasts.Any() ? forecasts.Min(x => x.Value.FetchUtc) : (DateTime?)null); }
static int Main(string[] args) { Parameter parameter = new Parameter(args); parameter.Port.All(c => { _portScanResult.Add(c, new PortScanResult { Host = parameter.Host, Port = c }); return(true); }); _portScanResult.All(dic => { ThreadPool.QueueUserWorkItem(new WaitCallback(Scan), dic); return(true); }); Console.WriteLine($"ポートスキャンを開始します4。{_portScanResult.Min(c => c.Value.Port)}-{_portScanResult.Max(c => c.Value.Port)}"); //WorkerThread Default 25 //PortThread Default 1000 ThreadPool.SetMaxThreads(100, 5000); // ThreadPool. _portScanResult.All(dic => { dic.Value.AutoResetEvent.WaitOne(); if (dic.Value.ResultMessage.IndexOf("開いています") >= 0) { Console.WriteLine(dic.Value.ResultMessage); } return(true); }); //Console.ReadKey(); return(0); #if false TcpClient tc = new TcpClient(AddressFamily.InterNetwork); try { if (args.Length != 2) { throw new SystemException("パラメータ数に間違いがあります。パラメータ1=ホスト名もしくは、IPアドレス、パラメータ2=ポート番号"); } var result = tc.BeginConnect(args[0], int.Parse(args[1]), null, null); //最大待ち時間は、21秒です。 var sucess = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2)); //TcpClientは21秒固定でタイム・アウトします。 //その場合は、sucessとなりますが、tc.Connectedがfalseとなります。 if (sucess && tc.Connected) { Console.Out.WriteLine("コネクションが開いています。"); } else { Console.Out.WriteLine("コネクションがひらいいません。タイムアウトが発生しました。"); } tc.Close(); return(0); } catch (SocketException ex) { Console.Out.WriteLine(ex.ToString()); return(-1); } catch (Exception e) { Console.Out.Write(e.ToString()); return(-2); } #endif }
public Dictionary <string, double> FingUsecases(uint count = 10) { Dictionary <string, double> ret = new Dictionary <string, double>(); foreach (var node in ProbabilityGraph.GetAllNodes()) { double x = (double)NodesProbability[node]; if (ret.Any()) { double min = ret.Min(pair => pair.Value); if (min < x) { if (ret.Count() >= count) { ret.Remove(ret.First(pair => Math.Abs(pair.Value - min) < 2 * Double.Epsilon).Key); } ret.Add(node.GetContent(), x); } } else { ret.Add(node.GetContent(), x); } foreach (var outgoingNode in ProbabilityGraph.GetOutgoingNodes(node)) { var tempOutgoingX = x * ProbabilityGraph.GetEdgeFreq(node, outgoingNode) * NodesProbability[outgoingNode]; double outgoingX = Math.Pow(tempOutgoingX, 1.0 / 3.0); if (ret.Any()) { double min = ret.Min(pair => pair.Value); if (min < outgoingX) { if (ret.Count() >= count) { ret.Remove(ret.First(pair => Math.Abs(pair.Value - min) < 2 * Double.Epsilon).Key); } ret.Add(node.GetContent() + "," + outgoingNode.GetContent(), outgoingX); } } else { ret.Add(node.GetContent() + "," + outgoingNode.GetContent(), outgoingX); } foreach (var outgoingNode2 in ProbabilityGraph.GetOutgoingNodes(outgoingNode)) { var tempOutgoingX2 = tempOutgoingX * ProbabilityGraph.GetEdgeFreq(outgoingNode, outgoingNode2) * NodesProbability[outgoingNode2]; double outgoingX2 = Math.Pow(tempOutgoingX2, 1.0 / 5.0); if (ret.Any()) { double min = ret.Min(pair => pair.Value); if (min < outgoingX2) { if (ret.Count() >= count) { ret.Remove(ret.First(pair => Math.Abs(pair.Value - min) < 2 * Double.Epsilon).Key); } ret.Add(node.GetContent() + "," + outgoingNode.GetContent() + "," + outgoingNode2.GetContent(), outgoingX2); } } else { ret.Add(node.GetContent() + "," + outgoingNode.GetContent() + "," + outgoingNode2.GetContent(), outgoingX2); } } } } return(ret); }
static void Main(string[] args) { //creat rolodex List <IRobber> rolodex = new List <IRobber>(); int i = 1; //the criminals LockSpecialist Bob = new LockSpecialist() { Name = "Bob", SkillLevel = 35, PercentageCut = 35, Type = "Lock Specialist", Index = i++ }; LockSpecialist Sally = new LockSpecialist() { Name = "Sally", SkillLevel = 50, PercentageCut = 50, Type = "Lock Specialist", Index = i++ }; Muscle Jamar = new Muscle() { Name = "Jamar", SkillLevel = 45, PercentageCut = 35, Type = "Muscle", Index = i++ }; Muscle Larry = new Muscle() { Name = "Larry", SkillLevel = 65, PercentageCut = 65, Type = "Muscle", Index = i++ }; Hacker Langston = new Hacker() { Name = "Langston", SkillLevel = 75, PercentageCut = 50, Type = "Hacker", Index = i++ }; Hacker Quinton = new Hacker() { Name = "Quinton", SkillLevel = 45, PercentageCut = 40, Type = "Hacker", Index = i++ }; //add robbers to the Rolodex rolodex.Add(Bob); rolodex.Add(Sally); rolodex.Add(Jamar); rolodex.Add(Larry); rolodex.Add(Langston); rolodex.Add(Quinton); //create your criminals Console.WriteLine("Create a Criminal from the options below"); Console.WriteLine("1.Hacker (Disables alarms)"); Console.WriteLine("2.Muscle (Disarms guards)"); Console.WriteLine("3.Lock Specialist (cracks vault)"); Console.WriteLine(); string userSelection; //do while to let user create some more criminals do { Console.Write("> "); string userChoice = Console.ReadLine(); userSelection = userChoice; if (userSelection == "1") { Console.WriteLine("Please create your Hacker"); Console.WriteLine(); Console.Write("Enter Skill Name: "); string name = Console.ReadLine(); Console.Write("Enter Skill Level: "); int skillLevel = int.Parse(Console.ReadLine()); Console.Write("Enter % needed out of 100: "); int percentageCut = int.Parse(Console.ReadLine()); rolodex.Add(new Hacker() { Name = name, SkillLevel = skillLevel, PercentageCut = percentageCut, Type = "Hacker", Index = i++ }); } if (userSelection == "2") { Console.Write("Please create your Muscle"); Console.Write("Enter Skill Name: "); string name = Console.ReadLine(); Console.Write("Enter Skill Level: "); int skillLevel = int.Parse(Console.ReadLine()); Console.Write("Enter % needed out of 100: "); int percentageCut = int.Parse(Console.ReadLine()); rolodex.Add(new Muscle() { Name = name, SkillLevel = skillLevel, PercentageCut = percentageCut, Type = "Muscle", Index = i++ }); } if (userSelection == "3") { Console.Write("Please create your Lock Specialist"); Console.Write("Enter Skill Name: "); string name = Console.ReadLine(); Console.Write("Enter Skill Level: "); int skillLevel = int.Parse(Console.ReadLine()); Console.Write("Enter % needed out of 100: "); int percentageCut = int.Parse(Console.ReadLine()); rolodex.Add(new LockSpecialist() { Name = name, SkillLevel = skillLevel, PercentageCut = percentageCut, Type = "Lock Specialist", Index = i++ }); } }while (userSelection != ""); // create a bank with ints set to random Random rnd = new Random(); Bank UsBank = new Bank() { CashOnHand = rnd.Next(50_000, 1_000_001), AlarmScore = rnd.Next(0, 101), VaultScore = rnd.Next(0, 101), SecurityGuardScore = rnd.Next(0, 101) }; // store and set bank Dictionary <string, int> banks = new Dictionary <string, int>(); banks.Add("Guards", UsBank.SecurityGuardScore); banks.Add("Vault", UsBank.VaultScore); banks.Add("Alarm", UsBank.AlarmScore); var MostSecure = banks.Max(max => max.Key); var vH = banks.Max(max => max.Value); Console.WriteLine($"Most Secure: {MostSecure} score of {vH}"); var LeastSecure = banks.Min(min => min.Key); var vL = banks.Max(max => max.Value); Console.WriteLine($"Least Secure: {LeastSecure} score of {vL}"); // print out rolodex foreach (var robber in rolodex) { Console.WriteLine(); Console.WriteLine("Criminal"); Console.WriteLine("------------------"); Console.WriteLine($"Name: {robber.Name}"); Console.WriteLine($"Type: {robber.Type}"); Console.WriteLine($"Skill Level: {robber.SkillLevel}"); Console.WriteLine($"% due: {robber.PercentageCut}"); Console.WriteLine($"Crew Member #: {robber.Index}"); Console.WriteLine(); } //number of criminals Console.WriteLine($"# of Criminals: {rolodex.Count}"); //list to hold crew List <IRobber> crew = new List <IRobber>(); Console.WriteLine("Enter the Crew Member #'s to add to your heist team"); Console.WriteLine("Select at least 1 member from each group(hacker,muscle,lock specialist)"); int userCrewInput; do { int userChoice = int.Parse(Console.ReadLine()); userCrewInput = userChoice; foreach (IRobber Member in rolodex) { if (userCrewInput == Member.Index) { crew.Add(Member); Console.WriteLine("Add another Crew Member enter 0 when finished adding"); } // Console.WriteLine("Thats not a number try again dummy!"); } } while (userCrewInput != 0); foreach (var teamMate in crew) { Console.WriteLine($"Crew Member: {teamMate.Name}"); Console.WriteLine($"Crew Member Speciality: {teamMate.Type}"); } foreach (IRobber theif in crew) { theif.PerformSkill(UsBank); } UsBank.Security(); if (UsBank.IsSecure) { Console.WriteLine("The heist failed!"); } else { Console.WriteLine("WE'RE RICH ####!"); } } }
/// <summary> /// The actual scheduling procedure /// </summary> private void Runner() { var scheduled = new Dictionary <long, DateTime>(); while (!m_terminate) { //TODO: As this is executed repeatedly we should cache it // to avoid frequent db lookups //Determine schedule list var lst = Program.DataConnection.Schedules; foreach (var sc in lst) { if (!string.IsNullOrEmpty(sc.Repeat)) { DateTime start; DateTime last = new DateTime(0, DateTimeKind.Utc); if (!scheduled.TryGetValue(sc.ID, out start)) { start = new DateTime(sc.Time.Ticks, DateTimeKind.Utc); last = sc.LastRun; } try { start = GetNextValidTime(start, last, sc.Repeat, sc.AllowedDays); } catch (Exception ex) { Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex); } //If time is exceeded, run it now if (start <= DateTime.UtcNow) { var jobsToRun = new List <Server.Runner.IRunnerData>(); //TODO: Cache this to avoid frequent lookups foreach (var id in Program.DataConnection.GetBackupIDsForTags(sc.Tags).Distinct().Select(x => x.ToString())) { //See if it is already queued var tmplst = from n in m_worker.CurrentTasks where n.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup select n.Backup; var tastTemp = m_worker.CurrentTask; if (tastTemp != null && tastTemp.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup) { tmplst.Union(new [] { tastTemp.Backup }); } //If it is not already in queue, put it there if (!tmplst.Any(x => x.ID == id)) { var entry = Program.DataConnection.GetBackup(id); if (entry != null) { jobsToRun.Add(Server.Runner.CreateTask(Duplicati.Server.Serialization.DuplicatiOperation.Backup, entry)); } } } //Caluclate next time, by adding the interval to the start until we have // passed the current date and time //TODO: Make this more efficient int i = 50000; while (start <= DateTime.UtcNow && i-- > 0) { try { start = GetNextValidTime(start, start.AddSeconds(1), sc.Repeat, sc.AllowedDays); } catch (Exception ex) { Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex); continue; } } Server.Runner.IRunnerData lastJob = jobsToRun.LastOrDefault(); if (lastJob != null && lastJob != null) { lock (m_lock) m_updateTasks[lastJob] = new Tuple <ISchedule, DateTime, DateTime>(sc, start, DateTime.UtcNow); } foreach (var job in jobsToRun) { m_worker.AddTask(job); } if (start < DateTime.UtcNow) { //TODO: Report this somehow continue; } } scheduled[sc.ID] = start; } } var existing = lst.ToDictionary(x => x.ID); //Sort them, lock as we assign the m_schedule variable lock (m_lock) m_schedule = (from n in scheduled where existing.ContainsKey(n.Key) orderby n.Value select new KeyValuePair <DateTime, ISchedule>(n.Value, existing[n.Key])).ToArray(); // Remove unused entries foreach (var c in (from n in scheduled where !existing.ContainsKey(n.Key) select n.Key).ToArray()) { scheduled.Remove(c); } //Raise event if needed if (NewSchedule != null) { NewSchedule(this, null); } int waittime = 0; //Figure out a sensible amount of time to sleep the thread if (scheduled.Count > 0) { //When is the next run scheduled? TimeSpan nextrun = scheduled.Min((x) => x.Value) - DateTime.UtcNow; if (nextrun.TotalMilliseconds < 0) { continue; } //Don't sleep for more than 5 minutes waittime = (int)Math.Min(nextrun.TotalMilliseconds, 60 * 1000 * 5); } else { //No tasks, check back later waittime = 60 * 1000; } //Waiting on the event, enables a wakeup call from termination // never use waittime = 0 m_event.WaitOne(Math.Max(100, waittime), false); } }
private void PictureBox_MouseUp(object sender, MouseEventArgs e) { _isMouseDown = false; _pixels.Clear(); for (int i = 0; i < _bitMap.Width; i++) { for (int j = 0; j < _bitMap.Height; j++) { var color = _bitMap.GetPixel(i, j); if (color.A == 255 && color.R == 0 && color.G == 0 && color.B == 0) { _pixels.Add(new Point(i, j), color); } } } if (_pixels.Count == 0) { return; } var leftTop = new Point(_pixels.Min(p => p.Key.X), _pixels.Min(p => p.Key.Y)); var rightBottom = new Point(_pixels.Max(p => p.Key.X), _pixels.Max(p => p.Key.Y)); var boundBitmap = new Bitmap(rightBottom.X - leftTop.X + 1, rightBottom.Y - leftTop.Y + 1); foreach (var pixel in _pixels) { boundBitmap.SetPixel(pixel.Key.X - leftTop.X, pixel.Key.Y - leftTop.Y, pixel.Value); } var stretchX = boundBitmap.Width / (float)pictureBox.Width; var stretchY = boundBitmap.Height / (float)pictureBox.Height; var stretchedBitmap = new Bitmap(100, 100); for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { var color = boundBitmap.GetPixel((int)(i * stretchX), (int)(j * stretchY)); stretchedBitmap.SetPixel(i, j, color); } } var cellValues = new int[_rowCellsCount * _rowCellsCount]; for (int i = 0; i < stretchedBitmap.Width; i++) { for (int j = 0; j < stretchedBitmap.Height; j++) { var color = stretchedBitmap.GetPixel(i, j); if (color.A == 255 && color.R == 0 && color.G == 0 && color.B == 0) { cellValues[(i / _splitValue) * _rowCellsCount + j / _splitValue]++; } } } for (int i = 0; i < _rowCellsCount * _rowCellsCount; i++) { if (cellValues[i] > 5) { _cells[i] = 1; } } }
public void demoDict1() { //Add Elements to dictionary dictObj1.Add(1, "prathmesh"); dictObj1.Add(2, "rahul"); dictObj1.Add(3, "aayan"); //find key value pair at location KeyValuePair <int, string> pair = dictObj1.ElementAt(1); Console.WriteLine(pair.Key + "***" + pair.Value); //find key value pair at first position KeyValuePair <int, string> pair2 = dictObj1.First(); Console.WriteLine(pair2.Key + "***" + pair2.Value); //find key value pair at first position KeyValuePair <int, string> pair3 = dictObj1.Last(); Console.WriteLine(pair3.Key + "***" + pair3.Value); //Find if key is present in dictionary if (dictObj1.ContainsKey(3)) { Console.WriteLine("Key present"); } else { Console.WriteLine("Key Not present"); } //Find if value present in dictionary if (dictObj1.ContainsValue("aayan")) { Console.WriteLine("Value Present"); } else { Console.WriteLine("Value Not Present"); } //loop through dictionary as key value pairs foreach (var item in dictObj1) { Console.WriteLine(item.Key + " " + item.Value); } //number of elements in dict Console.WriteLine("No of elements::" + dictObj1.Count); //Remove with key dictObj1.Remove(1); display_dictObj1(dictObj1); // order by keys in ascending order //dictObj1 = dictObj1.OrderBy(x=> x).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value); //display_dictObj1(dictObj1); //order by keys in desc order //dictObj1 = dictObj1.OrderByDescending(x => x).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value); //display_dictObj1(dictObj1); //return maximum value in key Console.WriteLine(dictObj1.Max(x => x.Key)); //return minimum value in value Console.WriteLine(dictObj1.Min(x => x.Value)); //convet dictionary to list List <KeyValuePair <int, string> > myList = dictObj1.ToList(); }
private static Row[] RemoveExtents(int testStage, Row rowmask, Row[] rows, out bool distinct) { testStage = 5; int position = 5; int extentLength = (int)Stage.GetFactorial(testStage); var rowGrps = rows.GroupBy(x => x[position]).OrderBy(y => y.Key); var newRows = new List <Row>(); foreach (var grp in rowGrps) { if (grp.Count() >= extentLength) { var ptable = new Dictionary <int, int>(); byte[] fixedbells = grp.First().ToArray(); foreach (var row in grp) { var hash = row.GetHashCode(); if (!ptable.TryAdd(hash, 1)) { ptable[hash]++; } // Determine fixed bells for (int i = 0; i < rows[0].Stage; i++) { if (row[i] != fixedbells[i]) { fixedbells[i] = 255; } } } // How many extents in the group int numExtents = ptable.Count < extentLength ? 0 : ptable.Min(x => x.Value); if (numExtents > 0) { // Use dictionary to control removal of the right number of rows ptable = ptable.ToDictionary(p => p.Key, p => numExtents); // Remove extents foreach (var row in grp) { var hash = row.GetHashCode(); if (ptable[hash] > 0) { ptable[hash]--; continue; } newRows.Add(row); } } Console.WriteLine($"Contains {numExtents} {Stage.GetName(testStage)} {Pluralise("extent", numExtents)} with {new Row(fixedbells)} as fixed bell(s)."); } else { newRows.AddRange(grp); } } // Check whether remaining rows are distinct distinct = true; var pt = new HashSet <int>(); foreach (var row in newRows) { var hash = row.GetHashCode(); if (!pt.Add(hash)) { distinct = false; break; } } if (distinct) { Console.WriteLine($"The remaining {newRows.Count} {Stage.GetName(testStage)} rows are distinct."); } return(newRows.ToArray()); }
async Task DownloadLeafAsync( ICursor cursor, Dictionary <DateTimeOffset, int> commitTimestampCount, BaseCatalogItem leafItem) { _logger.LogInformation("Downloading catalog leaf: {Url}", leafItem.Url); await DownloadAndParseAsync <JObject>(leafItem.Url); lock (commitTimestampCount) { var newCount = --commitTimestampCount[leafItem.CommitTimestamp]; if (newCount == 0) { commitTimestampCount.Remove(leafItem.CommitTimestamp); // Only write the timestamp if it's the last item in the commit and // it's the lowest commit timestamp of all pending leaves. if (commitTimestampCount.Count == 0 || leafItem.CommitTimestamp < commitTimestampCount.Min(x => x.Key)) { cursor.Write(leafItem.CommitTimestamp); } } } }
private void UpdatePixelMapping(Dictionary<int, Utility.PixelMap[]> input) { for (int i = 0; i < this.pixelMapping.Length; i++) this.pixelMapping[i] = -1; if (!input.Any()) return; int minUniverse = input.Min(x => x.Key); int maxUniverse = input.Max(x => x.Key); for (int universe = minUniverse; universe <= maxUniverse; universe++) { Utility.PixelMap[] mapping; if (!input.TryGetValue(universe, out mapping)) continue; for (int i = 0; i < mapping.Length; i++) { Utility.PixelMap map = mapping[i]; int rgbOffset = -1; switch (map.ColorComponent) { case Utility.ColorComponent.R: rgbOffset = 2; break; case Utility.ColorComponent.G: rgbOffset = 1; break; case Utility.ColorComponent.B: rgbOffset = 0; break; } if (rgbOffset == -1) continue; int sourcePos = map.Y * this.stride + map.X * 3 + rgbOffset; if (sourcePos >= 0 && sourcePos <= this.pixelMapping.Length) this.pixelMapping[sourcePos] = i + (universe - minUniverse) * 510; } } }