public static CraftingTable CreateCraftingTableModel(CraftingTable _model) { _model.CraftingTableId = currentCraftingTables.Count > 0 ? currentCraftingTables.LastOrDefault().Key + 1 : 1; currentCraftingTables.Add(_model.CraftingTableId, _model); SaveChanges(saveType.Model); return(currentCraftingTables.LastOrDefault().Value); }
// ************************************************************ // METHODS // ************************************************************ // Transaction : deposit & withdrawal public void Transaction(DateTime date, double amount) { // Update transaction records if (!_transactions.Keys.Contains(date)) { _transactions[date] = 0.0; } _transactions[date] = _transactions[date] + amount; // Compute interest rates double interestRate; DateTime previousDate = _balanceHistory.LastOrDefault().Key; if (_rate.Keys.Contains(previousDate)) { interestRate = _rate[previousDate]; } else { interestRate = _rate.LastOrDefault().Value; } // Compute applicable time double yearFraction; yearFraction = _dayCounter.yearFraction(new Date(previousDate), new Date(date)); // Update Balance _balanceHistory[date] = _balanceHistory.LastOrDefault().Value *(1.0 + interestRate * yearFraction) + amount; if (_balanceHistory[date] < (-1 * _maxBorrow)) { throw new ArgumentException("NegativeCashBalance", "Maximum borrowing level exceeded."); } }
private static void ToggleMenue() { Menu: Console.WriteLine("\n\n\n\n\nnull\tRun the latest solution\r\n--a\tRuns all \r\n--q\tQuit"); var input = Console.ReadLine(); if (input == "") { Console.Clear(); PrintSingleResult(ResultDelegates.LastOrDefault().Value, ResultDelegates.LastOrDefault().Key); Console.WriteLine("Press any key to continue.."); Console.ReadLine(); Console.Clear(); } else if (input == "--a") { Console.Clear(); PrintAllResults(); Console.WriteLine("Press any key to continue.."); Console.ReadLine(); Console.Clear(); } else if (input == "--q") { Environment.Exit(0); } else { Console.Clear(); } goto Menu; }
public void CifrarTexto(byte[] byteBuffer) { var texto = string.Empty; foreach (char letra in byteBuffer) { //se realiza la conversión de los caracteres var receptorValorOriginal = diccionarioOriginal.LastOrDefault(x => x.Key == Convert.ToString(letra)).Value; var receptorValorCifrado = diccionarioCifrado.LastOrDefault(x => x.Value == receptorValorOriginal).Key; if (receptorValorOriginal == 0) { receptorValorCifrado = Convert.ToString(letra); } texto += receptorValorCifrado; } using (var writeStream = new FileStream(RutaUsuario + "\\..\\Files\\archivoCifradoCesar.cif", FileMode.OpenOrCreate)) { using (var writer = new BinaryWriter(writeStream)) { writer.Seek(0, SeekOrigin.End); writer.Write(System.Text.Encoding.Unicode.GetBytes(texto)); } } }
public static void WriteReceiveLogsInFile() { try { /**/ if (!Directory.Exists("logs")) { Directory.CreateDirectory("logs"); } using (var sw = new StreamWriter(recfileName)) { foreach (var log in ReceiveLogs) { sw.WriteLine($"{log.Key} : {log.Value}"); } sw.WriteLine("\n\n\n"); var firstLog = ReceiveLogs.FirstOrDefault(); var lastLog = ReceiveLogs.LastOrDefault(); var difference = (DateTime.Parse(lastLog.Key) - DateTime.Parse(firstLog.Key)).TotalMilliseconds; var firstPublishLog = PublishLogs.FirstOrDefault(); var diff = (DateTime.Parse(lastLog.Key) - DateTime.Parse(firstPublishLog.Key)); sw.WriteLine($" First message received on {firstLog.Key} \n Last message received on {lastLog.Key} \n\n Time Elaspse {difference}ms"); sw.WriteLine($"\n\n Total time between first publish and last msg receive event is {diff.TotalMilliseconds}ms ~ {diff.TotalMinutes}minutes"); } } catch (Exception ex) { Console.WriteLine($"Exception WriteReceiveLogsInFile: {ex.StackTrace}"); } }
public string Descompress(Dictionary <string, int> diccionario, List <byte> ASCII, int CantidadBitsRequeridos, string RutaArchivo) { var textoDescompreso = string.Empty; var caracterPrevioDiccionario = string.Empty; var caracterActualDiccionario = string.Empty; var AuxiliarBitsRequeridos = string.Empty; var numeroBinario = string.Empty; LZWCompressor LZW = new LZWCompressor(); var ASCIIABYTE = new List <int>(); foreach (byte bit in ASCII) { numeroBinario = Convert.ToString(bit, 2); numeroBinario = numeroBinario.PadLeft(8, '0'); foreach (char caracter in numeroBinario) { AuxiliarBitsRequeridos += caracter; if (AuxiliarBitsRequeridos.Length == CantidadBitsRequeridos) { int valor = Convert.ToInt32(AuxiliarBitsRequeridos.Substring(0, CantidadBitsRequeridos), 2); var receptor = diccionario.LastOrDefault(x => x.Value == valor).Key; if (diccionario.Count() < valor) { valor = diccionario.Count(); receptor = diccionario.LastOrDefault(x => x.Value == valor).Key; receptor = receptor.Substring(0, 1); } foreach (char j in receptor) { caracterActualDiccionario += j; if (!diccionario.ContainsKey(caracterActualDiccionario)) { textoDescompreso += caracterPrevioDiccionario; diccionario.Add(caracterActualDiccionario, diccionario.Count() + 1); caracterActualDiccionario = string.Empty; caracterActualDiccionario += j; } caracterPrevioDiccionario = caracterActualDiccionario; } AuxiliarBitsRequeridos = string.Empty; } } } if (caracterActualDiccionario != string.Empty) { textoDescompreso += caracterActualDiccionario; } using (var writeStream = new FileStream(RutaArchivo + "\\..\\Files\\archivoDescomprimido.txt", FileMode.OpenOrCreate)) { using (var writer = new BinaryWriter(writeStream)) { writer.Write(System.Text.Encoding.Unicode.GetBytes(textoDescompreso)); } } textoDescompreso = string.Empty; return(textoDescompreso); }
public void ObtenerTextoArchivoOriginal(string archivoLeido) { var bufferLength = 10000; string CarpetaCompress = Environment.CurrentDirectory; if (!Directory.Exists(Path.Combine(CarpetaCompress, "CipherCesar2"))) { Directory.CreateDirectory(Path.Combine(CarpetaCompress, "CipherCesar2")); } using (var writeStream = new FileStream(Path.Combine(CarpetaCompress, "CipherCesar2", $"{RutaUsuario}.txt"), FileMode.OpenOrCreate)) { using (var writer = new BinaryWriter(writeStream)) { using (var stream = new FileStream(archivoLeido, FileMode.Open)) { using (var reader = new BinaryReader(stream)) { var byteBuffer = new byte[bufferLength]; //el buffer de lectura de archivo se utiliza indirectamente para la escritura del nuevo archivo tambien while (reader.BaseStream.Position != reader.BaseStream.Length) { byteBuffer = reader.ReadBytes(bufferLength); var texto = new List <int>(); foreach (var letra in byteBuffer) { int receptorValorOriginal; int receptorValorCifrado; if (diccionarioOriginal.ContainsKey(letra)) { receptorValorOriginal = diccionarioOriginal.LastOrDefault(x => x.Key == (letra)).Value; receptorValorCifrado = diccionarioCifrado.LastOrDefault(x => x.Value == receptorValorOriginal).Key; if (receptorValorOriginal == 0) { receptorValorCifrado = (letra); } } else { receptorValorCifrado = letra; } texto.Add(receptorValorCifrado); } foreach (var item in texto) { writer.Write(Convert.ToByte(Convert.ToChar(item))); } } } } } } }
private Dictionary <Station, DateTime> SetChangeTrainLineTime(Dictionary <Station, DateTime> stationTimeMap) { Dictionary <Station, DateTime> stationTimeMapModified = new Dictionary <Station, DateTime>(); var firstStation = stationTimeMap.FirstOrDefault(); int skipCounter = 0; foreach (var stations in stationTimeMap) { if (skipCounter != 0) { skipCounter--; continue; } if (stations.Equals(firstStation)) { stationTimeMapModified.Add(stations.Key, stations.Value); firstStation = stations; continue; } if (firstStation.Key.TrainLineId != stations.Key.TrainLineId) { var firstTime = firstStation.Value; var secondTime = stations.Value; int minuteDifference = Math.Abs(firstStation.Value.Minute - stations.Value.Minute); int compareResult = DateTime.Compare(firstTime, secondTime); if (compareResult == 0 || compareResult > 0) { var stationsToModify = stationTimeMap.Where(x => x.Key.TrainLineId == stations.Key.TrainLineId); skipCounter = stationsToModify.Count(); IncreaseTime(firstStation, stationsToModify, stationTimeMapModified); firstStation = stationTimeMapModified.LastOrDefault(); } else if (compareResult < 0 && minuteDifference < 10)// chaning a train adds 10 minutes { var stationsToModify = stationTimeMap.Where(x => x.Key.TrainLineId == stations.Key.TrainLineId); skipCounter = stationsToModify.Count(); IncreaseTime(firstStation, stationsToModify, stationTimeMapModified); firstStation = stationTimeMapModified.LastOrDefault(); } else { stationTimeMapModified.Add(stations.Key, stations.Value); firstStation = stations; } } else { stationTimeMapModified.Add(stations.Key, stations.Value); firstStation = stations; } } return(stationTimeMapModified); }
public Task <int> LastLogIndex() { var lastLog = _log.LastOrDefault(); if (lastLog.Value != null) { return(Task.FromResult(lastLog.Key)); } return(Task.FromResult(1)); }
/* * TODO: First pass: parse out existing things, the place we're in and decorators * Second pass: search for places in the world to make links * Third pass: More robust logic to avoid extra merging later */ private IEnumerable <IDictata> ParseSpeech(IList <Tuple <string, bool> > words) { /* * hello * hi there * did you go to the store * what are you doing there * I saw a red ball in the living room */ List <IDictata> returnList = new List <IDictata>(); ILocation currentPlace = _actor.CurrentLocation.CurrentLocation(); Dictionary <string, IDictata> brandedWords = BrandWords(words); string targetWord = string.Empty; //No valid nouns to make the target? Pick the last one if (!brandedWords.Any(ctx => ctx.Value == null)) { targetWord = brandedWords.LastOrDefault().Key; } else { targetWord = brandedWords.LastOrDefault(ctx => ctx.Value == null).Key; } brandedWords.Remove(targetWord); List <IDictata> descriptors = new List <IDictata>(); foreach (KeyValuePair <string, IDictata> adjective in brandedWords.Where(ctx => ctx.Value == null || (ctx.Value != null && (ctx.Value.WordType == LexicalType.Adjective || ctx.Value.WordType == LexicalType.Adverb)))) { if (adjective.Value != null) { descriptors.Add(adjective.Value); } else { descriptors.Add(new Dictata() { Name = adjective.Key, WordType = LexicalType.Adjective }); } } returnList.AddRange(descriptors); return(returnList); }
public IEnumerator Hide() { yield return(new WaitForSeconds(waitTime)); if (anim != null) { anim.Play("MessageBox_Hide"); } isShowing = false; if (queue.Count > 0) { Show(queue.LastOrDefault().Key, queue.LastOrDefault().Value); } }
public void Add(Driver Driver) { if (Driver == null) { return; } GetAll(); if (FakeDaoDriver == null) { return; } using (StreamWriter files = new StreamWriter(_connectionString)) { var lastIndex = FakeDaoDriver.LastOrDefault().Key; if (lastIndex == 0) { Driver.Id = lastIndex; FakeDaoDriver.Add(lastIndex++, Driver); } else { FakeDaoDriver.Add(++lastIndex, Driver); Driver.Id = lastIndex; } foreach (var driver in FakeDaoDriver.Values) { files.WriteLine($"{driver.Id} {driver.LastName} {driver.FistName} {driver.MiddleName}"); } } }
public static void Create(FactionInteractive _model) { _model.InteractiveID = currentFactionInteractives.Count > 0 ? currentFactionInteractives.LastOrDefault().Key + 1 : 1; _model.LabelOnMap = API.shared.createTextLabel(_model.Name, _model.Position, 15, 1, false, _model.Dimension); currentFactionInteractives.Add(_model.InteractiveID, _model); SaveChanges(); }
private static string TopologicalSort() { var res = new List <string>(); while (dependencies.Count > 0) { string nodeDelete; if (dependencies.Where(x => x.Value == 0).Count() > 1) { nodeDelete = dependencies.LastOrDefault(x => x.Value == 0).Key; } else { nodeDelete = dependencies.FirstOrDefault(x => x.Value == 0).Key; } res.Add(nodeDelete); foreach (var child in graph[nodeDelete]) { dependencies[child]--; } dependencies.Remove(nodeDelete); } return(string.Join(" ", res)); }
public Guid GetWindowID(UIElement element, string elementID) { var window = Window.GetWindow(element); if (window == null) { var lastWindow = myReferencedWindows.LastOrDefault(); if (lastWindow.Key == null) { return(Guid.Empty); } return(lastWindow.Value); } Guid guid; if (!myReferencedWindows.TryGetValue(window, out guid)) { guid = IsMainWindow(window) ? Guid.Empty : Guid.NewGuid(); myReferencedWindows.Add(window, guid); window.SizeChanged += WindowSizeChanged; window.LocationChanged += WindowLocationChanged; window.Deactivated += WinDeactivated; window.Activated += WinActivated; window.Closed += WindowClosed; } return(guid); }
public static void CreateHouse(House _model) { _model.HouseId = CurrentHousesDict.Count > 0 ? CurrentHousesDict.LastOrDefault().Key + 1 : 1; _model.InteriorDimension = _model.HouseId; HouseMarkerColor hmc = new HouseMarkerColor(); _model.LabelOnMap = API.shared.createTextLabel(_model.Name, _model.EntrancePosition, 10, 1, false, _model.EntranceDimension); _model.MarkerOnMap = API.shared.createMarker(_model.MarkerType, _model.EntrancePosition, new Vector3(), _model.EntranceRotation, new Vector3(1, 1, 1), 255, _model.IsSelling ? hmc.SaleColor.Red : hmc.NormalColor.Red, _model.IsSelling ? hmc.SaleColor.Green : hmc.NormalColor.Green, _model.IsSelling ? hmc.SaleColor.Blue : hmc.NormalColor.Blue, _model.EntranceDimension ); while (true) { try { CurrentHousesDict.Add(_model.HouseId, _model); break; } catch (Exception ex) { if (ex.GetType() == typeof(TargetInvocationException)) { _model.HouseId++; } } } //CurrentHousesDict.Add(_house, API.shared.createMarker(_house.MarkerType, _house.EntrancePosition, new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector3(1, 1, 1), 255, hmc.SaleColor.Red, hmc.SaleColor.Green, hmc.SaleColor.Blue, _house.EntranceDimension)); SaveChanges(); }
// public List<ExamProccessLog> ReadSubjectLog(int ClassId, int MainExamId, int SubjectId,int SectionId) // { // string strSQL = @"select epl.*,m.MainExamName,S.SectionName,t.Name TermName,c.ClassName,ss.SubjectName from dbo.Res_ExamProccessLog epl //INNER JOIN dbo.Res_MainExam m on m.MainExamId=epl.MainExamId //INNER JOIN dbo.Res_Terms T on T.TermId=m.TermId //Inner JOin dbo.Ins_ClassInfo c on c.ClassId=epl.ClassId //Inner JOin dbo.Ins_Section S on S.SectionId =epl.SectionId //Inner JOin dbo.Res_SubjectSetup ss on ss.SubID=epl.SubjectId WHERE epl.ClassId = " + ClassId + " AND epl.MainExamId = " + MainExamId + " AND epl.SubjectId = " + SubjectId + "AND epl.SectionId =" + SectionId; // strSQL = strSQL + " ORDER BY LogId desc"; // List<ExamProccessLog> lstlog = new List<ExamProccessLog>(); // DataTable dtResults = new DataTable(); // try // { // dtResults = SqlHelper.ExecuteDataTable(ConStr, CommandType.Text, strSQL); // if (dtResults.Rows.Count > 0) // { // foreach (DataRow dr in dtResults.Rows) // { // ExamProccessLog Log = new ExamProccessLog(); // Log.LogId = Convert.ToInt32(dr["LogId"]); // Log.MainExamId = Convert.ToInt32(dr["MainExamId"]); // Log.SessionId = Convert.ToInt32(dr["SessionId"]); // Log.ClassId = Convert.ToInt32(dr["ClassId"]); // Log.MainExamName = dr["MainExamName"].ToString(); // Log.TermName = dr["TermName"].ToString(); // Log.ClassName = dr["ClassName"].ToString(); // Log.SubjectName = dr["SubjectName"]==null ? string.Empty : dr["SubjectName"].ToString(); // Log.PId = dr["PId"].ToString(); // Log.Msg = dr["Msg"].ToString(); // Log.LogTime = Convert.ToDateTime(dr["LogTime"].ToString()); // Log.SectionName = dr["SectionName"].ToString(); // lstlog.Add(Log); // } // } // return lstlog; // } // catch (Exception ex) // { // throw ex; // } // } // public List<ExamProccessLog> ReadClassLog(int ClassId, int MainExamId,int SectionId) // { // string strSQL = @"select epl.*,m.MainExamName,S.SectionName,t.Name TermName,c.ClassName,ss.SubjectName from dbo.Res_ExamProccessLog epl //INNER JOIN dbo.Res_MainExam m on m.MainExamId=epl.MainExamId //INNER JOIN dbo.Res_Terms T on T.TermId=m.TermId //Inner JOin dbo.Ins_ClassInfo c on c.ClassId=epl.ClassId //Inner JOin dbo.Ins_Section S on S.SectionId =epl.SectionId // left JOin dbo.Res_SubjectSetup ss on ss.SubID=epl.SubjectId WHERE epl.SubjectId=0 and epl.ClassId = " + ClassId + " AND epl.MainExamId = " + MainExamId + "AND epl.SectionId =" + SectionId; // strSQL = strSQL + " ORDER BY LogId desc"; // List<ExamProccessLog> lstlog = new List<ExamProccessLog>(); // DataTable dtResults = new DataTable(); // try // { // dtResults = SqlHelper.ExecuteDataTable(ConStr, CommandType.Text, strSQL); // if (dtResults.Rows.Count > 0) // { // foreach (DataRow dr in dtResults.Rows) // { // ExamProccessLog Log = new ExamProccessLog(); // Log.LogId = Convert.ToInt32(dr["LogId"]); // Log.MainExamId = Convert.ToInt32(dr["MainExamId"]); // Log.SessionId = Convert.ToInt32(dr["SessionId"]); // Log.ClassId = Convert.ToInt32(dr["ClassId"]); // Log.MainExamName = dr["MainExamName"].ToString(); // Log.MainExamName = dr["TermName"].ToString(); // Log.MainExamName = dr["ClassName"].ToString(); // Log.PId = dr["PId"].ToString(); // Log.Msg = dr["Msg"].ToString(); // Log.LogTime = Convert.ToDateTime(dr["LogTime"].ToString()); // Log.SectionName = dr["SectionName"].ToString(); // lstlog.Add(Log); // } // } // return lstlog; // } // catch (Exception ex) // { // throw ex; // } // } // public List<ExamProccessLog> ReadLog(int ShiftId, int MainExamId, string pid) // { // //string Sql = @"UPDATE Res_Tabulation SET ExamName = '" + NewExamName + "' WHERE ExamName = '" + OldExam + "'"; // string strSQL = @"SELECT top 25 * FROM Res_ExamProccessLog WHERE ShiftId = " +ShiftId+ " AND MainExamId = " + MainExamId; // if (!string.IsNullOrEmpty(pid)) // // Sql = Sql + " AND MainExamId = " + ExamId; // strSQL = strSQL + " AND PId = '" + pid +"'"; // strSQL = strSQL + " ORDER BY LogId desc"; // List <ExamProccessLog> lstlog = new List<ExamProccessLog>(); // DataTable dtResults = new DataTable(); // try // { // dtResults = SqlHelper.ExecuteDataTable(ConStr, CommandType.Text, strSQL); // if(dtResults.Rows.Count>0) // { // foreach (DataRow dr in dtResults.Rows) // { // ExamProccessLog Log = new ExamProccessLog(); // Log.LogId = Convert.ToInt32( dr["LogId"]); // Log.MainExamId = Convert.ToInt32(dr["MainExamId"]); // Log.SessionId = Convert.ToInt32(dr["SessionId"]); // Log.ShiftID = Convert.ToInt32(dr["ShiftID"]); // Log.ClassId = Convert.ToInt32(dr["ClassId"]); // Log.PId = dr["PId"].ToString(); // Log.Msg = dr["Msg"].ToString(); // Log.LogTime = Convert.ToDateTime( dr["LogTime"].ToString()); // lstlog.Add(Log); // } // } // return lstlog; // } // catch (Exception ex) // { // throw ex; // } // } // public List<ExamProccessLog> ReadLogGrand(int ShiftId, int ClassId,int GroupId) // { // string strSQL = @"SELECT * FROM Res_ExamProccessLog WHERE ShiftId = " + ShiftId + // " AND ClassId = " + ClassId + " AND GroupId = " + GroupId + " AND PId = 'G' "; // strSQL = strSQL + " ORDER BY LogId desc"; // List<ExamProccessLog> lstlog = new List<ExamProccessLog>(); // DataTable dtResults = new DataTable(); // try // { // dtResults = SqlHelper.ExecuteDataTable(ConStr, CommandType.Text, strSQL); // if (dtResults.Rows.Count > 0) // { // foreach (DataRow dr in dtResults.Rows) // { // ExamProccessLog Log = new ExamProccessLog(); // Log.LogId = Convert.ToInt32(dr["LogId"]); // Log.MainExamId = Convert.ToInt32(dr["MainExamId"]); // Log.SessionId = Convert.ToInt32(dr["SessionId"]); // Log.ShiftID = Convert.ToInt32(dr["ShiftID"]); // Log.ClassId = Convert.ToInt32(dr["ClassId"]); // Log.PId = dr["PId"].ToString(); // Log.Msg = dr["Msg"].ToString(); // Log.LogTime = Convert.ToDateTime(dr["LogTime"].ToString()); // lstlog.Add(Log); // } // } // return lstlog; // } // catch (Exception ex) // { // throw ex; // } // } /// <summary> /// Dynamic Update Table by Raw Query /// </summary> /// <param name="ShiftId"></param> /// <param name="ClassId"></param> /// <param name="GroupId"></param> /// <returns></returns> public bool UpdateBySql(string TableName, Dictionary <string, string> Columns, Dictionary <string, string> WhereClauses, params SqlParameter[] sqlParameterlist) { string strSQL = @"UPDATE " + TableName + " SET "; foreach (var item in Columns) { strSQL += " " + item.Key + " = " + item.Value + " ,"; } strSQL = strSQL.Trim(','); strSQL += " WHERE ";// Set Where Clause foreach (var item in WhereClauses) { strSQL += " " + item.Key + " = " + item.Value; if (!WhereClauses.LastOrDefault().Equals(item)) { strSQL += " AND "; } } try { int Res = SqlHelper.ExecuteNonQuery(ConStr, CommandType.Text, strSQL, sqlParameterlist); return(Res > 0); } catch (Exception ex) { throw ex; } }
public PeanutsUserGroupMembershipStatistics(UserGroupMembership member, IList <Peanut> allPeanutsInGroup, IList <PeanutParticipation> peanutParticipationsOfMember) { /*Gruppe*/ TotalPeanutsInGroup = allPeanutsInGroup.Count; CanceledPeanutsInGroup = allPeanutsInGroup.Count(p => p.IsCanceled); PeanutsCreatedByMember = allPeanutsInGroup.Count(p => p.CreatedBy.Equals(member.User)); CurrentPeanutCount = allPeanutsInGroup.Count(p => p.PeanutState != PeanutState.Canceled && p.PeanutState != PeanutState.Realized); AvarageParticipationsCount = allPeanutsInGroup.Where(p => p.PeanutState != PeanutState.Canceled).Average(p => p.Participations.Count(part => part.ParticipationState == PeanutParticipationState.Confirmed)); DonePeanutsInGroup = allPeanutsInGroup.Count(p => p.PeanutState == PeanutState.Realized); /*Teilnahmen*/ ParticipationsOnCanceledPeanutsInGroup = peanutParticipationsOfMember.Count(part => part.ParticipationState == PeanutParticipationState.Confirmed && part.Peanut.IsCanceled); PeanutParticipationCountTotal = allPeanutsInGroup.Count(p => !p.IsCanceled); ParticipationsOnDonePeanutsInGroup = allPeanutsInGroup.Count(p => p.PeanutState == PeanutState.Realized); ParticipationsByType = peanutParticipationsOfMember .Where(part => !part.Peanut.IsCanceled) .GroupBy(part => part.ParticipationType) .ToDictionary(g => g.Key, g => g.Count()); PriceDevelopment = CalculatePriceDevelopment(member, allPeanutsInGroup); Dictionary <Peanut, double> orderedByPrice = PriceDevelopment.OrderBy(dev => dev.Value.Price).ToDictionary(o => o.Key, o => o.Value.Price); MinPrice = orderedByPrice.FirstOrDefault(); MaxPrice = orderedByPrice.LastOrDefault(); }
public T Get <T>() { var implementationType = _typeImplementationDependencies.LastOrDefault(serviceDescriptor => serviceDescriptor.Key == typeof(T) || serviceDescriptor.Value == typeof(T)).Value; if (implementationType == null) { throw new Exception($"The implementation for the {typeof(T)} wasn't found"); } var constructorParameters = implementationType.GetConstructors()[0].GetParameters(); var importedProperties = implementationType.GetProperties() .Where(prop => prop.GetCustomAttribute <ImportAttribute>() != null).ToList(); if (constructorParameters.Length > 0) { return(GetImplementationForTypeWithConstructor <T>(implementationType, constructorParameters)); } if (importedProperties.Any()) { return(GetImplementationForTypeWithImportedProperties <T>(implementationType, importedProperties)); } return((T)Activator.CreateInstance(implementationType)); }
public void Add(WorkItem workItem) { if (workItem == null) { return; } GetAll(); if (FakeDaoWorkItem == null) { return; } using (StreamWriter files = new StreamWriter(_connectionString)) { var lastIndex = FakeDaoWorkItem.LastOrDefault().Key; if (lastIndex == 0) { workItem.Id = lastIndex; FakeDaoWorkItem.Add(lastIndex++, workItem); } else { FakeDaoWorkItem.Add(++lastIndex, workItem); workItem.Id = lastIndex; } foreach (var item in FakeDaoWorkItem.Values) { files.WriteLine($"{item.Id} {item.WorkDate.Date:MM/dd/yyyy} " + $"{item.Driver.FistName} {item.Driver.MiddleName} {item.Driver.LastName} " + $"{item.Car.Mark}"); } } }
public static void LoadTimedMail() { string filePath = HttpRuntime.AppDomainAppPath + "configs/TimedMail.bytes"; if (!File.Exists(filePath)) { return; } using (FileStream stream = File.OpenRead(filePath)) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); //for (int i = 0; i < stream.Length; ++i) //{ // buffer[i] = (byte)(buffer[i] ^ 0x37); //} using (BinaryReader reader = new BinaryReader(new MemoryStream(buffer))) { string json = reader.ReadString(); m_dicTimedMails = JsonConvert.DeserializeObject <Dictionary <int, STTimedMail> >(json); m_dicTimedMails = m_dicTimedMails.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value); _nextId = m_dicTimedMails.LastOrDefault().Key + 1; } } }
void Update() { if (MLHands.IsStarted) { _statusText.text = $"Hand tracking has started..."; AddAndUpdateHandKeyPoint(new FingerKeyPoint[] { new FingerKeyPoint { Name = $"HandLeft.{nameof(MLHands.Left.Index)}", KeyPoint = MLHands.Left.Index.KeyPoints[0] }, new FingerKeyPoint { Name = $"HandRight.{nameof(MLHands.Right.Index)}", KeyPoint = MLHands.Right.Index.KeyPoints[0] }, }); if (cacheKeyPoints.Count > 0) { leftHandFinger = cacheKeyPoints.FirstOrDefault().Value; rightHandFinger = cacheKeyPoints.LastOrDefault().Value; // update source and target line measureLine.SetPosition(0, leftHandFinger.transform.position); measureLine.SetPosition(1, rightHandFinger.transform.position); distanceText.text = $"DISTANCE: {(Vector3.Distance(leftHandFinger.transform.position, rightHandFinger.transform.position) * measurementFactor).ToString("F2")} in"; } _statusText.text = $"Hand Key Points: {string.Join(",", cacheKeyPoints.Keys.Select(s => s).ToArray())}"; } else { _statusText.text = $"Hand tracking has not started..."; } }
// Managers private async Task <IConnection> GetOrCreateConnection(bool forceCreation = false) { IConnection conn; var poolItem = _connPool.LastOrDefault(x => x.Value.Count() < _connConfig.ChannelsPerConnection); // Prevent returning a closed connection if (!IsNull(poolItem) && !poolItem.Key.IsOpen) { await RemoveConnection(poolItem.Key); poolItem = default; } if (IsNull(poolItem) || forceCreation) { var connFactory = _connConfig.CreateConnectionFactory(); conn = await connFactory.CreateConnectionAsync(); _connPool[conn] = new List <IModel>(); } else { conn = poolItem.Key; } return(conn); }
private string GetFullUrl(string url, Dictionary <string, object> query = null) { StringBuilder fullUrl = new StringBuilder(this.m_serverUrl); fullUrl.Append(url); // dictionary key value pair to query string StringBuilder encodedQuery = new StringBuilder(); if (query != null) { foreach (var kvp in query) { if (query.FirstOrDefault().Key == kvp.Key) { fullUrl.Append("?"); } fullUrl.AppendFormat("{0}={1}", kvp.Key, HttpUtility.UrlEncode(kvp.Value.ToString())); if (query.LastOrDefault().Key != kvp.Key) { fullUrl.Append("&"); } } } return(fullUrl.ToString()); }
private Dictionary <string, XDocument> GetAssemblesWithDocuments(XDocument xmlDocument) { var documents = new Dictionary <string, XDocument>(); foreach (var member in xmlDocument.Elements("doc").Elements("members").Elements("member")) { var memberName = member.Attribute("name"); if (memberName != null && memberName.Value.Contains("T:")) { var assembleyName = member.Attribute("name").Value.Split('.')[1]; documents.Add(assembleyName, new XDocument(new XElement("doc", new XElement("assembly", new XElement("name", assembleyName)), new XElement("members", member) ))); continue; } var document = documents.LastOrDefault(); var members = document.Value.Elements("doc").Elements("members").FirstOrDefault(); if (members != null) { members.Add(member); } } return(documents); }
public static void Create(Business _model) { _model.BusinessId = currentBusiness.Count > 0 ? currentBusiness.LastOrDefault().Value.BusinessId + 1 : 1; _model.LabelOnMap = API.shared.createTextLabel(_model.BusinessName, _model.Position, 10, 1, true, _model.Dimension); currentBusiness.Add(_model.BusinessId, _model); SaveChanges(); }
public decimal GetTaxResult(decimal income) { var maxLevel = _percentLookup.LastOrDefault(m => m.Key < income); return(maxLevel.Key == _percentLookup.First().Key ? maxLevel.Value * income : maxLevel.Value *(income - maxLevel.Key) + GetTaxResult(maxLevel.Key)); }
public void Add(TKey key, TValue value) { if (!_sorted) { _order.Add(key, _order.LastOrDefault().Value + 1); } _internalList.Add(key, value); }
private void ProcessManifest(string data, string filename) { JsonDocument jdoc = JsonDocument.Parse(data); JsonElement jroot = jdoc.RootElement; string packageName = string.Empty; string packageDesc = string.Empty; string packageAuthor = string.Empty; Version packageVersion = new Version(0, 0, 0); if (jroot.TryGetProperty("Name", out JsonElement nameProp)) { packageName = nameProp.GetString(); } if (jroot.TryGetProperty("Description", out JsonElement descProp)) { packageDesc = descProp.GetString(); } if (jroot.TryGetProperty("Author", out JsonElement authorProp)) { packageAuthor = authorProp.GetString(); } if (jroot.TryGetProperty("Version", out JsonElement versionProp)) { packageVersion = new Version(versionProp.GetString()); } if (manifestHeaders.ContainsKey(packageName)) { Log.WriteError($"Manifest with name {packageName} is already loaded. Aborting read operation."); return; } Log.WriteLine($"Loading manifest: {packageName} by {packageAuthor} (v {packageVersion.ToString(3)}), {packageDesc}"); string relativePath = Path.GetRelativePath(Environment.CurrentDirectory, filename); relativePath = Path.GetDirectoryName(relativePath); JsonElement resElement = jroot.GetProperty("Resources"); List <string> validResHeaders = new List <string>(); foreach (JsonElement ele in resElement.EnumerateArray()) { ProcessManifestEntry(ele, relativePath, ref validResHeaders); ResourceHeader lastHeader = headers.LastOrDefault().Value; if (lastHeader != null && !lastHeader.manifests.Contains(packageName)) //check is necessary since an entry can be discarded if malformed. { lastHeader.manifests.Add(packageName); } } ManifestHeader manifestHeader = new ManifestHeader(packageName, packageAuthor, packageDesc, packageVersion, validResHeaders.ToArray(), filename); manifestHeaders.Add(manifestHeader.name, manifestHeader); Log.WriteLine("Manifest " + manifestHeader.name + " loaded. " + manifestHeader.headerNames.Length + " headers processed."); }
public object GetNativeId(Security security) { if (security == null) { throw new ArgumentNullException(nameof(security)); } return(_nativeIdSecurities.LastOrDefault(p => p.Value == security).Key); }
private Dictionary<DateTime, decimal> Process(DateTime fromDate) { /* * Unfortunately because EMA's rely on previous ema processed data and the first EMA is aways the SMA * we always have to process the entire data set every time so it remains consistent for partial updates */ var orderedClosingPrices = this.closingPrices.OrderBy(p => p.Key); var startingEmaValue = Math.Round(orderedClosingPrices.Take(this.timePeriod).Average(e => e.Value), 2); var startingEmaDate = orderedClosingPrices.Skip(timePeriod - 1).First().Key; var multiplier = (decimal)2 / (decimal)(this.timePeriod + 1); var ema = new Dictionary<DateTime, decimal> { { startingEmaDate, startingEmaValue } }; var closingPricesToWorkWith = this.closingPrices.Where(e => e.Key > startingEmaDate).OrderBy(e => e.Key); foreach (var closingPrice in closingPricesToWorkWith) { var yesterdayEma = ema.LastOrDefault(); ema.Add(closingPrice.Key, Math.Round(((closingPrice.Value - yesterdayEma.Value) * multiplier + yesterdayEma.Value), 2)); } return ema.Where(d => d.Key >= fromDate).ToDictionary(d => d.Key, d => d.Value); }
/// <summary> /// average Data By Week /// </summary> /// <param name="conductivityData">conductivity Data</param> /// <param name="sourceNumber">source Number</param> private void AverageDataByWeek(Dictionary<DateTime, Tuple<int, int>> conductivityData, int sourceNumber) { try { DateTime firstDate = new DateTime(); if (conductivityData != null && conductivityData.Count > 0) { firstDate = conductivityData.FirstOrDefault().Key; } DateTime lastDate = new DateTime(); if (conductivityData != null && conductivityData.Count > 0) { lastDate = conductivityData.LastOrDefault().Key; } int weeks = Convert.ToInt32(((lastDate - firstDate).TotalDays / 7) + 1); DateTime previousDate = new DateTime(); if (conductivityData != null && conductivityData.Count > 0) { previousDate = conductivityData.FirstOrDefault().Key; } int nextWeek = 0; if (conductivityData != null && conductivityData.Count > 0) { nextWeek = WeekNumberCalculator(conductivityData.LastOrDefault().Key.AddDays(7)); } List<int>[] groupedWeekCondData = new List<int>[weeks]; int i = 0; foreach (var entry in conductivityData) { int currentWeek = WeekNumberCalculator(entry.Key); int average; if (currentWeek != nextWeek && !this.dataForWeekToAverage.ContainsKey(entry.Key)) { this.dataForWeekToAverage.Add(entry.Key, entry.Value); } else { List<int> valuesForWeek = new List<int>(); foreach (var condVal in this.dataForWeekToAverage.Values) { valuesForWeek.Add(condVal.Item2); } if (this.dataForWeekToAverage.Count == 0) { valuesForWeek.Add(entry.Value.Item2); } groupedWeekCondData[i] = valuesForWeek; average = Convert.ToInt32(valuesForWeek.Average()); Tuple<int, int, List<int>> weekCondVal = new Tuple<int, int, List<int>>(currentWeek, average, groupedWeekCondData[i]); if (!this.weeklyAverageCondDataSource1.ContainsKey(entry.Key)) { if (sourceNumber == 1) { this.weeklyAverageCondDataSource1.Add(entry.Key, weekCondVal); } else { this.weeklyAverageCondDataSource2.Add(entry.Key, weekCondVal); } } nextWeek = WeekNumberCalculator(entry.Key.AddDays(7)); this.dataForWeekToAverage.Clear(); i++; } previousDate = entry.Key; } } catch { throw; } }
private bool loadAndCheckArguments(string[] args) { print_about(); if (args == null || args.Length == 0) { print_help(); return false; } // Parsing Arguments file_with_list = null; dest_dir = null; flags = new Dictionary<string, object>(); string[] empty_flags = new string[] { "i", "interface" }; foreach (var arg in args) { var last = flags.LastOrDefault(); if (flags.Count > 0 && last.Value == null && !empty_flags.Any(x => x == last.Key)) { flags[last.Key] = arg; continue; } // Flag if (arg.StartsWith("-")) { flags[arg.Substring(1).ToLower()] = null; } else { if (file_with_list == null) file_with_list = arg; else if (dest_dir == null) dest_dir = arg; } } //Process flags for (var i = 0; i < flags.Count; i++) { var flag = flags.ElementAt(i); switch (flag.Key) { case "threads": case "t": int c; flags["threads"] = int.TryParse(flag.Value.ToString(), out c) ? c : -1; break; case "interface": case "i": //without value flags["interface"] = null; break; } } //Interface call if (flags.ContainsKey("interface")) { var result = ParamsForm.OpenDialog(); if (result != null) { file_with_list = null; file_list = result.Links.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); dest_dir = result.DestinationFolder; flags["threads"] = result.ThreadCount; } else if (file_with_list == null) { print_help(); return false; } } //Check file list and load links if (file_list == null && !File.Exists(file_with_list)) { print_text(string.Format("Error: File \"{0}\" doesn't exists.", file_with_list)); return false; } else if (file_list == null) { file_list = File.ReadAllLines(file_with_list).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray(); } //Output parameter try { if (!Directory.Exists(dest_dir)) Directory.CreateDirectory(dest_dir); } catch { dest_dir = "."; } dest_dir = Path.GetFullPath(dest_dir); return true; }
public static IList<ApTimeLine> GetPlayerApTimeline(Player p, string patch, int matchId, int teamId) { try { IList<ApTimeLine> timelines = new List<ApTimeLine>(); var orderedTime = p.ItemTimeLine.OrderBy(a => a.TimeStamp).ToList(); IDictionary<int, double> apPerMin = new Dictionary<int, double>(); var items = new List<Item>(); var groups = orderedTime.GroupBy(a => (int)Math.Truncate((double)a.TimeStamp / 60000)); var runesAp = p.Runes.Sum(r => r.Ap); var runesApPerLv = p.Runes.Sum(r => r.ApPerLevel); var runesMr = p.Runes.Sum(r => r.MagicResist); var runesMrPerLv = p.Runes.Sum(r => r.MagicResistPerLevel); foreach (var group in groups) { try { var t = new ApTimeLine(); t.Minute = group.Key; var lv = p.TimeLine[t.Minute].Level; t.PlayerId = p.ParticipantId; t.MatchId = matchId; t.TeamId = teamId; foreach (var itemTimeline in group) { Item item; if (patch.StartsWith("5.11")) item = ItemsCache.GetItemV511(itemTimeline.ItemId); else item = ItemsCache.GetItemV514(itemTimeline.ItemId); double itemAp = 0; if (itemTimeline.EventType == "ITEM_PURCHASED") { items.Add(item); } else { items.Remove(item); } double totalAp = items.Sum(i => ItemStats.GetTotalAP(i,t.Minute,p.SelectedChampion)) + runesAp + runesApPerLv * lv; if (items.Any(i => i.Name == "Rabadon's Deathcap")) { if (patch.StartsWith("5.11")) totalAp = totalAp * 1.30; else totalAp = totalAp * 1.35; } if (apPerMin.ContainsKey(t.Minute)) { apPerMin[t.Minute] = totalAp; } else { apPerMin.Add(new KeyValuePair<int, double>(t.Minute, totalAp)); } } t.Items = items.ToList(); t.CurrentGold = p.TimeLine[t.Minute].CurrentGold; t.GoldSpent = items.Sum(i => i.GoldCost); t.TotalMr = items.Sum(i => i.ItemStats.MR) + p.SelectedChampion.Stat.MagicResist + p.SelectedChampion.Stat.MagicResistPerLv * lv + runesMr + runesMrPerLv * lv; ; t.TotalAp = apPerMin.LastOrDefault().Value; timelines.Add(t); } catch { throw; } } return timelines; } catch { throw; } }
//-------------------------------------------------------NearestWard------------------------------------------- public static Obj_AI_Minion NearestWard() { if (!ObjectManager.Get<Obj_AI_Minion>().Where(ward => ward.IsAlly && ward.Name.ToLower().Contains("ward") && Geometry.Distance(ward.ServerPosition, Game.CursorPos) < 1900 && Geometry.Distance(Player.ServerPosition, ward.ServerPosition) <= Program.W.Range).Any()) return null; Dictionary<Obj_AI_Minion, float> Distances = new Dictionary<Obj_AI_Minion, float>(); Vector3 Mousepos = Game.CursorPos; int i = new int(); i = 0; foreach (Obj_AI_Minion Ward in ObjectManager.Get<Obj_AI_Minion>().Where(ward => ward.IsAlly && ward.Name.ToLower().Contains("ward") && Geometry.Distance(ward.ServerPosition, Game.CursorPos) < 1900 && Geometry.Distance(Player.ServerPosition, ward.ServerPosition) <= Program.W.Range)) { if (i != 0 && Geometry.Distance(Ward.ServerPosition, Mousepos) <= Distances.LastOrDefault().Value)//If the new ward is at a shorter distance. { Distances.Remove(Distances.LastOrDefault().Key);//Remove the last ward. Distances.Add(Ward, Geometry.Distance(Ward.ServerPosition, Mousepos));//Here, we add the new ward to the dictionary. } else if (i != 0 && Geometry.Distance(Ward.ServerPosition, Mousepos) >= Distances.LastOrDefault().Value)//If the new ward is at a greater distance. we don't do nothing. { } else//First ward found in the loop. { Distances.Add(Ward, Geometry.Distance(Ward.ServerPosition, Mousepos));//As a first ward, we simply add it. } i += 1; } if (Distances.LastOrDefault().Key.IsValid) return Distances.LastOrDefault().Key; else return null; }
public Result SearchK2(int N, double delta) { Dictionary<int, double> K2_dic = new Dictionary<int, double>(); K2_dic.Add(100, 1.0); K2_dic.Add(200, 1.03); K2_dic.Add(300, 1.06); K2_dic.Add(500, 1.09); K2_dic.Add(700, 1.14); K2_dic.Add(900, 1.20); K2_dic.Add(1000, 1.32); K2_dic.Add(2000, 1.49); K2_dic.Add(3000, 1.55); K2_dic.Add(4000, 1.65); K2_dic.Add(5000, 1.77); K2_dic.Add(10000, 1.90); K2_dic.Add(20000, 2.03); K2_dic.Add(30000, 2.16); K2_dic.Add(40000, 2.35); K2_dic.Add(50000, 2.90); K2_dic.Add(60000, 3.0); K2_dic.Add(80000, 3.0); K2_dic.Add(100000, 3.0); Result result = new Result(); var maximum = K2_dic.FirstOrDefault(x => x.Key > N); if (maximum.Key == 0) { Result max = new Result(); max.key = 100000; max.value = 3; //return max; } var minimum = K2_dic.LastOrDefault(x => x.Key < N); Result bottom = new Result(); bottom.key = minimum.Key; bottom.value = minimum.Value; Result upper = new Result(); upper.key = maximum.Key; upper.value = maximum.Value; result.key = ((upper.key + bottom.key) / 2.0); result.value = ((upper.value + bottom.value) / 2.0); while (Math.Abs(N - result.key) > delta) { if (N < result.key) { upper = result; } else { bottom = result; } result.key = ((upper.key + bottom.key) / 2.0); result.value = ((upper.value + bottom.value) / 2.0); } return result; }
public static Obj_AI_Minion NearestWard(IEnumerable<Obj_AI_Minion> Wards) { if (!Wards.Any()) return null; Dictionary<Obj_AI_Minion, float> Distances = new Dictionary<Obj_AI_Minion, float>(); Vector3 Mousepos = Game.CursorPos; int i = new int(); i = 0; foreach (Obj_AI_Minion Ward in Wards) { if (i != 0 && Geometry.Distance(Ward.ServerPosition, Mousepos) <= Distances.LastOrDefault().Value)//If the new ward is at a shorter distance. { Distances.Remove(Distances.LastOrDefault().Key);//Remove the last ward. Distances.Add(Ward, Geometry.Distance(Ward.ServerPosition, Mousepos));//Here, we add the new ward to the dictionary. } else if (i != 0 && Geometry.Distance(Ward.ServerPosition, Mousepos) >= Distances.LastOrDefault().Value)//If the new ward is at a greater distance. we don't do nothing. { } else//First ward found in the loop. { Distances.Add(Ward, Geometry.Distance(Ward.ServerPosition, Mousepos));//As a first ward, we simply add it. } i += 1; } if (Distances.LastOrDefault().Key.IsValid) return Distances.LastOrDefault().Key; else return null; }