public static async Task <List <Genre> > OrderGenresAsync(IList <Genre> genres, GenreOrder genreOrder) { var orderedGenres = new List <Genre>(); await Task.Run(() => { switch (genreOrder) { case GenreOrder.Alphabetical: orderedGenres = genres.OrderBy((g) => FormatUtils.GetSortableString(g.GenreName, true)).ToList(); break; case GenreOrder.ReverseAlphabetical: orderedGenres = genres.OrderByDescending((g) => FormatUtils.GetSortableString(g.GenreName, true)).ToList(); break; default: // Alphabetical orderedGenres = genres.OrderBy((g) => FormatUtils.GetSortableString(g.GenreName, true)).ToList(); break; } }); return(orderedGenres); }
protected override void GetPlayBackServiceProgress() { base.GetPlayBackServiceProgress(); this.CurrentTime = FormatUtils.FormatTime(this.playBackService.GetCurrentTime); this.TotalTime = FormatUtils.FormatTime(this.playBackService.GetTotalTime); }
public void CompareFormatTest() { CultureInfo origCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Assert.AreEqual("N0", FormatUtils.CompareFormat(double.NaN, "<", 0.0008, "N0")); Assert.AreEqual("N0", FormatUtils.CompareFormat(0.0001, "<", double.NaN, "N0")); Assert.AreEqual("N0", FormatUtils.CompareFormat(double.NegativeInfinity, "<", 0.0008, "N0")); Assert.AreEqual("N0", FormatUtils.CompareFormat(0.0001, "<", double.PositiveInfinity, "N0")); Assert.AreEqual("N1", FormatUtils.CompareFormat(0.5, "<", 1, "N0")); Assert.AreEqual("N1", FormatUtils.CompareFormat(0.3, "<", 0.6, "N0")); Assert.AreEqual("N2", FormatUtils.CompareFormat(3.95, ">", 3.94, "N0")); Assert.AreEqual("N3", FormatUtils.CompareFormat(0.007, "<", 0.008, "N0")); Assert.AreEqual("N4", FormatUtils.CompareFormat(0.0007, "<", 0.0008, "N0")); Assert.AreEqual("N4", FormatUtils.CompareFormat(0.00001, "<", 0.0008, "N0")); } finally { Thread.CurrentThread.CurrentCulture = origCulture; } }
public IActionResult Pesquisar(string cpf, string nome) { var clientes = this.clienteRepository.List(); if (!string.IsNullOrEmpty(cpf)) { clientes = clientes.Where(x => x.CPF == FormatUtils.ConverterStringParaCPF(cpf)).ToList(); } if (!string.IsNullOrEmpty(nome)) { clientes = clientes.Where(x => x.Nome.ToLower().Contains(nome.ToLower().Trim())).ToList(); } var clientesViewModel = new List <SelecaoClienteViewModel>(); if (clientes != null) { foreach (var item in clientes) { clientesViewModel.Add(new SelecaoClienteViewModel { Cpf = item.CPF.ToString(), Nome = item.Nome, IsSelecionado = false }); } } return(PartialView("~/Views/Cliente/Partial/ListagemSelecaoCliente.cshtml", clientesViewModel)); }
private string GetDescription( [NotNull] ICollection <ParallelSegmentPair> relatedPairs, double maxAngleOffset, out IssueCode issueCode) { double azimuthDiffDeg = MathUtils.ToDegrees(maxAngleOffset); double azimuthToleranceDeg = MathUtils.ToDegrees(_azimuthToleranceRad); string angleFormat = FormatUtils.CompareFormat( azimuthDiffDeg, ">", azimuthToleranceDeg, "N1"); string offsetDescription = string.Format("{0} > {1}", FormatAngle(maxAngleOffset, angleFormat), FormatAngle(_azimuthToleranceRad, angleFormat)); if (relatedPairs.Count == 1) { issueCode = Codes[Code.AzimuthsSimilarButNotEqual_SegmentPair]; return(string.Format( "The two segments have similar, but not equal azimuths (azimuth difference: {0})", offsetDescription)); } issueCode = Codes[Code.AzimuthsSimilarButNotEqual_SegmentGroup]; return(string.Format( "The segments of this group have similar, but not equal azimuths (maximum azimuth difference: {0})", offsetDescription)); }
private void cmdTest_Click(object sender, EventArgs e) { if (DoValidate()) { string lastStep = "Initialize values"; try { Cursor.Current = Cursors.WaitCursor; RegistryQueryCollectorConfigEntry testQueryInstance = new RegistryQueryCollectorConfigEntry(); testQueryInstance.Name = txtName.Text; testQueryInstance.UseRemoteServer = chkUseRemoteServer.Checked; testQueryInstance.Server = txtServer.Text; testQueryInstance.Path = txtPath.Text; testQueryInstance.KeyName = txtKey.Text; testQueryInstance.ExpandEnvironmentNames = chkExpandEnvNames.Checked; testQueryInstance.RegistryHive = RegistryQueryCollectorConfigEntry.GetRegistryHiveFromString(cboRegistryHive.Text); if (!chkValueIsANumber.Checked) { testQueryInstance.ReturnValueIsNumber = false; testQueryInstance.ReturnValueInARange = false; testQueryInstance.ReturnValueInverted = false; } else { testQueryInstance.ReturnValueIsNumber = true; testQueryInstance.ReturnValueInARange = chkValueIsInARange.Checked; testQueryInstance.ReturnValueInverted = !chkReturnValueNotInverted.Checked; } testQueryInstance.SuccessValue = cboSuccessValue.Text; testQueryInstance.WarningValue = cboWarningValue.Text; testQueryInstance.ErrorValue = cboErrorValue.Text; object returnValue = null; returnValue = testQueryInstance.GetValue(); CollectorState state = testQueryInstance.EvaluateValue(returnValue); if (state == CollectorState.Good) { MessageBox.Show(string.Format("Success!\r\nValue return: {0}", FormatUtils.FormatArrayToString(returnValue)), "Test", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (state == CollectorState.Warning) { MessageBox.Show(string.Format("Warning!\r\nValue return: {0}", FormatUtils.FormatArrayToString(returnValue)), "Test", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { MessageBox.Show(string.Format("Error!\r\nValue return: {0}", FormatUtils.FormatArrayToString(returnValue)), "Test", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show(string.Format("Failed!\r\nLast step: {0}\r\n{1}", lastStep, ex.Message), "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } finally { Cursor.Current = Cursors.Default; } } }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if (!filterContext.HttpContext.Request.IsAjaxRequest()) { CurrentDb.SysPageAccessRecord.Add(new SysPageAccessRecord() { UserId = User.Identity.GetUserId <int>(), AccessTime = DateTime.Now, PageUrl = filterContext.HttpContext.Request.Url.AbsolutePath, Ip = CommonUtils.GetIP() }); CurrentDb.SaveChanges(); } ILog log = LogManager.GetLogger(CommonSetting.LoggerAccessWeb); log.Info(FormatUtils.AccessWeb(User.Identity.GetUserId <int>(), User.Identity.GetUserName())); bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); if (!skipAuthorization) { if (filterContext.HttpContext.Request.Url.AbsolutePath.IndexOf(WebBackConfig.GetLoginPage()) == -1) { if (Request.IsAuthenticated) { var userId = User.Identity.GetUserId <int>(); var user = CurrentDb.SysStaffUser.Where(m => m.Id == userId).FirstOrDefault(); if (user == null) { Response.Redirect(WebBackConfig.GetLoginPage() + "?out=0"); } } } } }
public static async Task VideoToFrames(string inputFile, string framesDir, bool alpha, float rate, bool deDupe, bool delSrc, Size size) { Logger.Log("Extracting video frames from input video..."); string sizeStr = (size.Width > 1 && size.Height > 1) ? $"-s {size.Width}x{size.Height}" : ""; IOUtils.CreateDir(framesDir); string timecodeStr = /* timecodes ? $"-copyts -r {FrameOrder.timebase} -frame_pts true" : */ "-frame_pts true"; string mpStr = deDupe ? ((Config.GetInt("mpdecimateMode") == 0) ? mpDecDef : mpDecAggr) : ""; string filters = FormatUtils.ConcatStrings(new string[] { GetPadFilter(), mpStr }); string vf = filters.Length > 2 ? $"-vf {filters}" : ""; string rateArg = (rate > 0) ? $" -r {rate.ToStringDot()}" : ""; string pixFmt = alpha ? "-pix_fmt rgba" : "-pix_fmt rgb24"; // Use RGBA for GIF for alpha support string args = $"{rateArg} {GetTrimArg(true)} -i {inputFile.Wrap()} {compr} -vsync 0 {pixFmt} {timecodeStr} {vf} {sizeStr} {GetTrimArg(false)} \"{framesDir}/%{Padding.inputFrames}d.png\""; LogMode logMode = Interpolate.currentInputFrameCount > 50 ? LogMode.OnlyLastLine : LogMode.Hidden; await RunFfmpeg(args, logMode, TaskType.ExtractFrames, true); int amount = IOUtils.GetAmountOfFiles(framesDir, false, "*.png"); Logger.Log($"Extracted {amount} {(amount == 1 ? "frame" : "frames")} from input.", false, true); await Task.Delay(1); if (delSrc) { DeleteSource(inputFile); } }
public void CanTestInDegrees() { IFeatureClass fc = CreateLineClass(_testWs, "CanTestInDegrees"); IFeature row1 = fc.CreateFeature(); row1.Shape = CurveConstruction.StartLine(0, 0, 0) .LineTo(0, 1, 0) .LineTo(0.1, 0, 0) .LineTo(0.1, 1, 100) .LineTo(0.1, 2, 100) .CircleTo(GeometryFactory.CreatePoint(0.2, 0, 100)) .Curve; row1.Store(); double limit = FormatUtils.Radians2AngleInUnits(0.1, AngleUnit.Degree); var test = new QaMinSegAngle(fc, limit, true); test.AngularUnit = AngleUnit.Degree; var runner = new QaContainerTestRunner(1000, test); runner.Execute(); Assert.AreEqual(2, runner.Errors.Count); }
//public override MonitorState RefreshState() //{ // MonitorState returnState = new MonitorState(); // string lastAction = ""; // int errors = 0; // int success = 0; // int warnings = 0; // double totalValue = 0; // try // { // RegistryQueryCollectorConfig currentConfig = (RegistryQueryCollectorConfig)AgentConfig; // returnState.RawDetails = string.Format("Running {0} registry query(s)", currentConfig.Entries.Count); // returnState.HtmlDetails = string.Format("<b>Running {0} registry query(s)</b>", currentConfig.Entries.Count); // foreach (RegistryQueryCollectorConfigEntry queryInstance in currentConfig.Entries) // { // object value = null; // if (queryInstance.UseRemoteServer) // lastAction = string.Format("Running Registry query '{0}' on '{1}'", queryInstance.Name, queryInstance.Server); // else // lastAction = string.Format("Running Registry query '{0}'", queryInstance.Name); // value = queryInstance.GetValue(); // if (!queryInstance.ReturnValueIsNumber && value.IsNumber()) // totalValue += double.Parse(value.ToString()); // CollectorState instanceState = queryInstance.EvaluateValue(value); // if (instanceState == CollectorState.Error) // { // errors++; // returnState.ChildStates.Add( // new MonitorState() // { // ForAgent = queryInstance.Name, // State = CollectorState.Error, // CurrentValue = value, // RawDetails = string.Format("'{0}' - value '{1}' - Error (trigger {2})", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]"), queryInstance.ErrorValue), // HtmlDetails = string.Format("'{0}' - value '{1}' - <b>Error</b> (trigger {2})", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]"), queryInstance.ErrorValue), // }); // } // else if (instanceState == CollectorState.Warning) // { // warnings++; // returnState.ChildStates.Add( // new MonitorState() // { // ForAgent = queryInstance.Name, // State = CollectorState.Warning, // CurrentValue = value, // RawDetails = string.Format("'{0}' - value '{1}' - Warning (trigger {2})", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]"), queryInstance.WarningValue), // HtmlDetails = string.Format("'{0}' - value '{1}' - <b>Warning</b> (trigger {2})", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]"), queryInstance.WarningValue), // }); // } // else // { // success++; // returnState.ChildStates.Add( // new MonitorState() // { // ForAgent = queryInstance.Name, // State = CollectorState.Good, // CurrentValue = value, // RawDetails = string.Format("'{0}' - value '{1}'", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]")), // HtmlDetails = string.Format("'{0}' - value '{1}'", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]")), // }); // } // } // if (errors > 0 && warnings == 0) // returnState.State = CollectorState.Error; // else if (warnings > 0) // returnState.State = CollectorState.Warning; // else // returnState.State = CollectorState.Good; // returnState.CurrentValue = totalValue; // } // catch (Exception ex) // { // returnState.RawDetails = ex.Message; // returnState.HtmlDetails = string.Format("<p><b>Last action:</b> {0}</p><blockquote>{1}</blockquote>", lastAction, ex.Message); // returnState.State = CollectorState.Error; // } // return returnState; //} public override List <System.Data.DataTable> GetDetailDataTables() { List <System.Data.DataTable> tables = new List <System.Data.DataTable>(); System.Data.DataTable dt = new System.Data.DataTable(); try { dt.Columns.Add(new System.Data.DataColumn("Path", typeof(string))); dt.Columns.Add(new System.Data.DataColumn("Value", typeof(string))); RegistryQueryCollectorConfig currentConfig = (RegistryQueryCollectorConfig)AgentConfig; foreach (RegistryQueryCollectorConfigEntry entry in currentConfig.Entries) { object value = entry.GetValue(); if (value.GetType().IsArray) { value = FormatUtils.FormatArrayToString(value); } dt.Rows.Add(entry.Description, value); } } catch (Exception ex) { dt = new System.Data.DataTable("Exception"); dt.Columns.Add(new System.Data.DataColumn("Text", typeof(string))); dt.Rows.Add(ex.ToString()); } tables.Add(dt); return(tables); }
public void showBookReviewDetail(BookReview data) { Glide.With(mContext) .Load(Constant.IMG_BASE_URL + data.review.author.avatar) //.Placeholder(Resource.Drawable.avatar_default) .Transform(new GlideCircleTransform(mContext)) .Into(headerViewHolder.ivAuthorAvatar); headerViewHolder.tvBookAuthor.Text = (data.review.author.nickname); headerViewHolder.tvTime.Text = (FormatUtils.getDescriptionTimeFromDateString(data.review.created)); headerViewHolder.tvTitle.Text = (data.review.title); headerViewHolder.tvContent.Text = (data.review.content); Glide.With(mContext) .Load(Constant.IMG_BASE_URL + data.review.book.cover) //.Placeholder(Resource.Drawable.cover_default) .Transform(new GlideRoundTransform(mContext)) .Into(headerViewHolder.ivBookCover); headerViewHolder.tvBookTitle.Text = (data.review.book.title); headerViewHolder.tvHelpfullYesCount.Text = data.review.helpful.yes.ToString(); headerViewHolder.tvHelpfullNoCount.Text = data.review.helpful.no.ToString(); headerViewHolder.tvCommentCount.Text = (Java.Lang.String.Format(mContext.GetString(Resource.String.comment_comment_count), data.review.commentCount)); headerViewHolder.rlBookInfo.Click += (sender, e) => { BookDetailActivity.startActivity(this, data.review.book._id); }; headerViewHolder.ratingBar.setCountSelected(data.review.rating); }
private string UpdateText(string originalString, BlueGreenContext userContext) { if (originalString != null) { originalString = originalString.Replace("{availablepoints}", userContext.GetPoints().ToString("N0")); if (originalString.Contains("{futurepoints}") && userContext.GetFuturePoints() == 0) { originalString = ""; } else { originalString = originalString.Replace("{futurepoints}", userContext.GetFuturePoints().ToString("N0")); } originalString = originalString.Replace("{ownershiplevel}", userContext.GetOwnershipLevel()); originalString = originalString.Replace("{bluegreenrewards}", FormatUtils.FormatPoints(userContext.GetRewards().ToString())); originalString = originalString.Replace("{expirationdate}", UiUtils.ConvertDateToString(userContext.OwnerExpiration)); originalString = originalString.Replace("{paymentbalance}", userContext.GetBalance().ToString("C")); if (!string.IsNullOrEmpty(userContext.GetAvailableWeek())) { originalString = originalString.Replace("{availableweeks}", userContext.GetAvailableWeek()); } } return(originalString); }
public MilkyManager() { KeyboardListener = KeyboardListener.GetOrNewInstance(); ConsoleLoops = ConsoleLoops.GetOrNewInstance(); LoopsManager = LoopsManager.GetOrNewInstance(); StatisticsLoops = StatisticsLoops.GetOrNewInstance(); OutputSettings = OutputSettings.GetOrNewInstance(); ProgramInformations = ProgramInformations.GetOrNewInstance(); ProgramManager = ProgramManager.GetOrNewInstance(); RunInformations = RunInformations.GetOrNewInstance(); RunLists = RunLists.GetOrNewInstance(); RunManager = RunManager.GetOrNewInstance(); ConsoleSettings = ConsoleSettings.GetOrNewInstance(); RunSettings = RunSettings.GetOrNewInstance(); CustomStatistics = CustomStatistics.GetOrNewInstance(); RunStatistics = RunStatistics.GetOrNewInstance(); ConsoleUtils = ConsoleUtils.GetOrNewInstance(); DateTimeUtils = DateTimeUtils.GetOrNewInstance(); FileUtils = FileUtils.GetOrNewInstance(); FormatUtils = FormatUtils.GetOrNewInstance(); HashUtils = HashUtils.GetOrNewInstance(); ListUtils = ListUtils.GetOrNewInstance(); RequestUtils = RequestUtils.GetOrNewInstance(); StringUtils = StringUtils.GetOrNewInstance(); UserUtils = UserUtils.GetOrNewInstance(); }
public void SubmitComboResult(string combo, ResultType resultType, CaptureDictionary captures = null, bool outputResult = true, string file = null, string directory = null) { _runInformations = RunInformations.GetOrNewInstance(); _formatUtils = FormatUtils.GetOrNewInstance(); _fileUtils = FileUtils.GetOrNewInstance(); _consoleUtils = ConsoleUtils.GetOrNewInstance(); if (resultType != ResultType.Invalid) { Interlocked.Increment(ref _runInformations.hits); if (resultType == ResultType.Free) { Interlocked.Increment(ref _runInformations.free); } if (outputResult) { string output = _formatUtils.FormatOutput(combo, captures != null ? _formatUtils.CaptureDictionaryToString(captures) : null); _fileUtils.WriteLine(output, $"{file ?? (resultType == ResultType.Free ? "Free" : "Hits")}.txt", directory ?? $"Results/{_runInformations.runStartFormattedDate}"); _consoleUtils.WriteLine(output, resultType == ResultType.Free ? ConsoleColor.Cyan : ConsoleColor.Green); } } Interlocked.Increment(ref _runInformations.ran); }
public string getTotalPressureLossByType(MEPSection section, SectionMemberType eType) { string strVal = ""; if (section != null) { double dVal = 0.0; if (eType == SectionMemberType.Segment) { List <MEPCurve> curves = new List <MEPCurve>(); SectionsInfo.getSectionElements(section, curves, null, null, null); foreach (MEPCurve crv in curves) { dVal += section.GetPressureDrop(crv.Id); } } else if (eType == SectionMemberType.Fitting) { List <FamilyInstance> fittings = new List <FamilyInstance>(); SectionsInfo.getSectionElements(section, null, fittings, null, null); foreach (FamilyInstance famInst in fittings) { dVal += section.GetPressureDrop(famInst.Id); } } else if (eType == SectionMemberType.AirTerminal) { List <FamilyInstance> airTerminals = new List <FamilyInstance>(); SectionsInfo.getSectionElements(section, null, null, airTerminals, null); foreach (FamilyInstance famInst in airTerminals) { dVal += section.GetPressureDrop(famInst.Id); } } else if (eType == SectionMemberType.Equipment) { List <FamilyInstance> equipments = new List <FamilyInstance>(); SectionsInfo.getSectionElements(section, null, null, null, equipments); foreach (FamilyInstance famInst in equipments) { dVal += section.GetPressureDrop(famInst.Id); } } if (eType == SectionMemberType.Section) { dVal = section.TotalPressureLoss; } if (domain == ReportResource.pipeDomain) { strVal = FormatUtils.Format(doc, UnitType.UT_Piping_Pressure, dVal); } else { strVal = FormatUtils.Format(doc, UnitType.UT_HVAC_Pressure, dVal); } } return(strVal); }
private string FormatLength(double value, string format) { string s = string.Format("{0} {1}", FormatUtils.GetValueString(value, format), _unitString); return(s); }
public override void setData(CommentList.CommentsBean item) { if (!Settings.IsNoneCover) { holder.setCircleImageUrl(Resource.Id.ivBookCover, Constant.IMG_BASE_URL + item.author.avatar, Resource.Drawable.avatar_default); } else { holder.setImageResource(Resource.Id.ivBookCover, Resource.Drawable.avatar_default); } holder.setText(Resource.Id.tvBookTitle, item.author.nickname) .setText(Resource.Id.tvContent, item.content) .setText(Resource.Id.tvBookType, Java.Lang.String.Format(mContext.GetString(Resource.String.book_detail_user_lv), item.author.lv)) .setText(Resource.Id.tvFloor, Java.Lang.String.Format(mContext.GetString(Resource.String.comment_floor), item.floor)) .setText(Resource.Id.tvTime, FormatUtils.getDescriptionTimeFromDateString(item.created)); if (item.replyTo == null) { holder.setVisible(Resource.Id.tvReplyNickName, false); holder.setVisible(Resource.Id.tvReplyFloor, false); } else { holder.setText(Resource.Id.tvReplyNickName, Java.Lang.String.Format(mContext.GetString(Resource.String.comment_reply_nickname), item.replyTo.author.nickname)) .setText(Resource.Id.tvReplyFloor, Java.Lang.String.Format(mContext.GetString(Resource.String.comment_reply_floor), item.replyTo.floor)); holder.setVisible(Resource.Id.tvReplyNickName, true); holder.setVisible(Resource.Id.tvReplyFloor, true); } }
private void ResetToEmptyGraph() { var now = DateTime.UtcNow; var earliest = (now - window - epoch).TotalSeconds; var latest = (now - epoch).TotalSeconds; // Put points on the far left, so we get a line from them this.inboundSeries.Points.Clear(); this.inboundSeries.Points.Add(new DataPoint(earliest, 0)); this.inboundSeries.Points.Add(new DataPoint(latest, 0)); this.outboundSeries.Points.Clear(); this.outboundSeries.Points.Add(new DataPoint(earliest, 0)); this.outboundSeries.Points.Add(new DataPoint(latest, 0)); this.xAxis.Minimum = earliest; this.xAxis.Maximum = latest; this.yAxis.Maximum = minYValue; this.MaxYValue = FormatUtils.BytesToHuman(minYValue) + "/s"; if (this.IsActive) { this.OxyPlotModel.InvalidatePlot(true); } }
public override MonitorState GetCurrentState() { string returnedData = ""; CollectorState agentState = CollectorState.NotAvailable; try { returnedData = ExecuteCommand(); CurrentAgentValue = FormatUtils.FormatArrayToString(returnedData, "[null]"); agentState = CollectorAgentReturnValueCompareEngine.GetState(ReturnCheckSequence, GoodResultMatchType, GoodValue, WarningResultMatchType, WarningValue, ErrorResultMatchType, ErrorValue, CurrentAgentValue); } catch (Exception wsException) { agentState = CollectorState.Error; returnedData = wsException.Message; } MonitorState currentState = new MonitorState() { ForAgent = Description, State = agentState, CurrentValue = returnedData == null ? "N/A" : returnedData, CurrentValueUnit = OutputValueUnit }; return(currentState); }
private void Update(SyncthingConnectionStats stats) { var now = DateTime.UtcNow; double earliest = (now - window - epoch).TotalSeconds; this.Update(earliest, this.inboundSeries, stats.InBytesPerSecond); this.Update(earliest, this.outboundSeries, stats.OutBytesPerSecond); this.xAxis.Minimum = earliest; this.xAxis.Maximum = (now - epoch).TotalSeconds; // This increases the value to the nearest 1024 boundary double maxValue = this.inboundSeries.Points.Concat(this.outboundSeries.Points).Max(x => x.Y); double roundedMax; if (maxValue > minYValue) { double factor = Math.Pow(1024, (int)Math.Log(maxValue, 1024)); roundedMax = Math.Ceiling(maxValue / factor) * factor; } else { roundedMax = minYValue; } // Give the graph a little bit of headroom, otherwise the line gets chopped this.yAxis.Maximum = roundedMax * 1.05; this.MaxYValue = FormatUtils.BytesToHuman(roundedMax) + "/s"; if (this.IsActive) { this.OxyPlotModel.InvalidatePlot(true); } }
public IActionResult Create(ClienteViewModel clienteViewModel) { if (ModelState.IsValid) { try { var cpf = FormatUtils.ConverterStringParaCPF(clienteViewModel.Cpf); var existente = this.clienteRepository.Get(x => x.CPF == cpf); if (existente != null) { ModelState.AddModelError("Cpf", "Não é possível cadastrar cliente. CPF duplicado!"); return(View(clienteViewModel)); } this.clienteRepository.Create((Cliente)clienteViewModel); TempData["sucesso"] = "Cadastro realizado com sucesso!"; return(RedirectToAction("Index", "Home")); } catch (Exception ex) { TempData["erro"] = $"Ocorreu um erro durante o processamento. Mensagem: {ex.Message}."; return(RedirectToAction("Index", "Home")); } } return(View(clienteViewModel)); }
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (!(holder is MachineStateViewHolder cell) || _statesLogs.Count <= position) { return; } var item = _statesLogs[position]; cell.IvState.SetImageBitmap(ResourcesHelper.GetImageFromResources(item.state.iconName)); cell.TvSateName.Text = !string.IsNullOrEmpty(item.description) ? item.description : item.state.name; cell.TvStartDate.Text = item.timeStart.ToString("dd.MM.yy HH:mm:ss"); if (item.timeEnd > item.timeStart) { cell.TvPeriod.Text = FormatUtils.PeriodStr(item.timeStart, item.timeEnd); cell.TvHourGlass.Visibility = ViewStates.Visible; } else { cell.TvPeriod.Text = null; cell.TvHourGlass.Visibility = ViewStates.Invisible; } cell.TvUser.Text = item.userName; }
protected void ApplyModifierTo(ref float value, string modifierValue) { if (FormatUtils.ParseFloat(modifierValue, out float multiplier)) { value *= multiplier; } }
private void DadosDaEmpresa(Int32 IdEmpresaCadastro, Int32 IdPrograma) { EntEmpresaCadastro objEmpresaCadastro = new BllEmpresaCadastro().ObterPorId(IdEmpresaCadastro); EntTurmaEmpresa objTurmaEmpresa = new BllTurmaEmpresa().ObterPorIdEmpresaIdPrograma(objEmpresaCadastro.IdEmpresaCadastro, IdPrograma); objTurmaEmpresa.AtividadeEconomica = new BllAtividadeEconomica().ObterPorId(objTurmaEmpresa.AtividadeEconomica.IdAtividadeEconomica); this.lblRazaoSocial.Text = objEmpresaCadastro.RazaoSocial; this.lblNomeFantasia.Text = objEmpresaCadastro.NomeFantasia; this.lblCategoria.Text = objTurmaEmpresa.Categoria.Categoria; this.lblCNAE.Text = objTurmaEmpresa.AtividadeEconomica.Codigo + " - " + objTurmaEmpresa.AtividadeEconomica.AtividadeEconomica; this.lblAtividadeEconomicaTxt.Text = objTurmaEmpresa.AtividadeEconomicaComplemento; this.lblCPFCNPJ.Text = FormatUtils.FormataCNPJ_CPF(objEmpresaCadastro.CPF_CNPJ); this.lblFaturamento.Text = objTurmaEmpresa.Faturamento.Faturamento; this.lblEmpregados.Text = IntUtils.ToString(objTurmaEmpresa.NumeroFuncionario); this.lblDataAbertura.Text = objEmpresaCadastro.AberturaEmpresa.ToShortDateString(); this.lblBairro.Text = objTurmaEmpresa.Bairro.Bairro; this.lblEndereco.Text = objTurmaEmpresa.Endereco; this.lblCEP.Text = FormatUtils.FormatCEP(objTurmaEmpresa.CEP); this.lblCidade.Text = objTurmaEmpresa.Cidade.Cidade; this.lblEstado.Text = objTurmaEmpresa.Estado.Estado; this.lblContatoNome.Text = objTurmaEmpresa.NomeContato; this.lblContatoCargo.Text = objTurmaEmpresa.Cargo.Cargo; this.lblContatoTelefone.Text = FormatUtils.FormatTelefone(objTurmaEmpresa.TelefoneContato); this.lblContatoCelular.Text = FormatUtils.FormatTelefone(objTurmaEmpresa.CelularContato); this.lblContatoEmail.Text = objTurmaEmpresa.EmailContato; }
private string GetQIValue(ListViewItem lvi, OLEDBQueryInstance queryInstance) { string results = ""; try { object value = queryInstance.RunQuery(); CollectorState currentstate = queryInstance.GetState(value); results = FormatUtils.N(value, "[null]"); if (currentstate == CollectorState.Error) { lvi.ImageIndex = 3; } else if (currentstate == CollectorState.Warning) { lvi.ImageIndex = 2; } else { lvi.ImageIndex = 1; } } catch (Exception ex) { results = ex.Message; } return(results); }
private void GetFileMetadata(string path) { try { if (!File.Exists(path)) { return; } var fm = new FileMetadata(path); this.SongTitle = fm.Title.Value; this.SongAlbum = fm.Album.Value; this.SongArtists = string.Join(", ", fm.Artists.Values); this.SongGenres = string.Join(", ", fm.Genres.Values); this.SongYear = fm.Year.Value.ToString(); this.SongTrackNumber = fm.TrackNumber.Value.ToString(); this.AudioDuration = FormatUtils.FormatTime(fm.Duration); this.AudioType = fm.Type; this.AudioSampleRate = string.Format("{0} {1}", fm.SampleRate.ToString(), "Hz"); this.AudioBitrate = string.Format("{0} {1}", fm.BitRate.ToString(), "kbps"); } catch (Exception ex) { LogClient.Error("Error while getting file Metadata. Exception: {0}", ex.Message); } }
public static async Task CreateSymlinksParallel(Dictionary <string, string> pathsLinkTarget, bool debug = false, int maxThreads = 150) { Stopwatch sw = new Stopwatch(); sw.Restart(); ParallelOptions opts = new ParallelOptions() { MaxDegreeOfParallelism = maxThreads }; Task forEach = Task.Run(async() => Parallel.ForEach(pathsLinkTarget, opts, pair => { bool success = CreateSymbolicLink(pair.Key, pair.Value, Flag.Unprivileged); if (debug) { Logger.Log($"Created Symlink - Source: '{pair.Key}' - Target: '{pair.Value}' - Sucess: {success}", true); } })); while (!forEach.IsCompleted) { await Task.Delay(1); } Logger.Log($"Created {pathsLinkTarget.Count} symlinks in {FormatUtils.TimeSw(sw)}", true); }
public static void UpdateInterpProgress(int frames, int target, string latestFramePath = "") { if (I.canceled) { return; } interpolatedInputFramesCount = ((frames / I.current.interpFactor).RoundToInt() - 1); //ResumeUtils.Save(); frames = frames.Clamp(0, target); int percent = (int)Math.Round(((float)frames / target) * 100f); Program.mainForm.SetProgress(percent); float generousTime = ((AiProcess.processTime.ElapsedMilliseconds - AiProcess.lastStartupTimeMs) / 1000f); float fps = ((float)frames / generousTime).Clamp(0, 9999); string fpsIn = (fps / currentFactor).ToString("0.00"); string fpsOut = fps.ToString("0.00"); if (fps > peakFpsOut) { peakFpsOut = fps; } float secondsPerFrame = generousTime / (float)frames; int framesLeft = target - frames; float eta = framesLeft * secondsPerFrame; string etaStr = FormatUtils.Time(new TimeSpan(0, 0, eta.RoundToInt()), false); bool replaceLine = Regex.Split(Logger.textbox.Text, "\r\n|\r|\n").Last().Contains("Average Speed: "); string logStr = $"Interpolated {frames}/{target} Frames ({percent}%) - Average Speed: {fpsIn} FPS In / {fpsOut} FPS Out - "; logStr += $"Time: {FormatUtils.Time(AiProcess.processTime.Elapsed)} - ETA: {etaStr}"; if (AutoEncode.busy) { logStr += " - Encoding..."; } Logger.Log(logStr, false, replaceLine); try { if (!string.IsNullOrWhiteSpace(latestFramePath) && frames > currentFactor) { if (bigPreviewForm == null && !preview.Visible /* ||Program.mainForm.WindowState != FormWindowState.Minimized */ /* || !Program.mainForm.IsInFocus()*/) { return; // Skip if the preview is not visible or the form is not in focus } if (timeSinceLastPreviewUpdate.IsRunning && timeSinceLastPreviewUpdate.ElapsedMilliseconds < previewUpdateRateMs) { return; } Image img = IoUtils.GetImage(latestFramePath, false, false); SetPreviewImg(img); } } catch (Exception e) { //Logger.Log("Error updating preview: " + e.Message, true); } }
public void UpdateState() { switch (this.FileTransfer.Status) { case FileTransferStatus.InProgress: if (this.FileTransfer.DownloadBytesPerSecond.HasValue) { this.ProgressString = String.Format(Resources.FileTransfersTrayView_Downloading_RateKnown, FormatUtils.BytesToHuman(this.FileTransfer.BytesTransferred), FormatUtils.BytesToHuman(this.FileTransfer.TotalBytes), FormatUtils.BytesToHuman(this.FileTransfer.DownloadBytesPerSecond.Value, 1)); } else { this.ProgressString = String.Format(Resources.FileTransfersTrayView_Downloading_RateUnknown, FormatUtils.BytesToHuman(this.FileTransfer.BytesTransferred), FormatUtils.BytesToHuman(this.FileTransfer.TotalBytes)); } this.ProgressPercent = ((float)this.FileTransfer.BytesTransferred / (float)this.FileTransfer.TotalBytes) * 100; break; case FileTransferStatus.Completed: this.ProgressPercent = 100; this.ProgressString = null; break; } this.Error = this.FileTransfer.Error; }
private PointsSummary GetPointsSummaryData(PointsSummary model) { DebugUtils.StartLogEvent("OwnerController.GetPointsSummaryData"); BlueGreenContext bgContext = new BlueGreenContext(); string ownerId = bgContext.OwnerId; model.AnnualPoints = "0"; model.SavedPoints = "0"; model.RestrictedPoints = "0"; model.AvailablePoints = "0"; try { ProfileService service = new ProfileService(); RestOwnerPointsResponse result = service.GetOwnerPoints(ownerId, null); if (result != null && result.Account != null && result.Account.Memberships != null && result.Account.Memberships.VacationClubMembership != null && result.Account.Memberships.VacationClubMembership.Points != null) { model.AnnualPoints = FormatUtils.FormatPoints(result.Account.Memberships.VacationClubMembership.Points.TotalAnnualPoints); model.SavedPoints = FormatUtils.FormatPoints(result.Account.Memberships.VacationClubMembership.Points.TotalSavedPoints); model.RestrictedPoints = FormatUtils.FormatPoints(result.Account.Memberships.VacationClubMembership.Points.TotalRestrictedPoints); model.AvailablePoints = FormatUtils.FormatPoints(result.Account.Memberships.VacationClubMembership.Points.TotalPoints); } } catch (Exception ex) { Sitecore.Diagnostics.Log.Error("Unexpected exception retreiving points for " + ownerId, ex, bgContext); } DebugUtils.EndLogEvent("OwnerController.GetPointsSummaryData"); return(model); }