static void Main(string[] args) { // create the subject and observers WeatherData weatherData = new WeatherData(); CurrentConditions conditions = new CurrentConditions(weatherData); Statistics statistics = new Statistics(weatherData); Forecast forecast = new Forecast(weatherData); // create the readings WeatherMeasurements readings = new WeatherMeasurements(); readings.humidity = 40.5F; readings.pressure = 20F; readings.temperature = 72F; // update the readings - everyone should print weatherData.UpdateReadings(readings); // update readings.pressure = 10F; weatherData.UpdateReadings(readings); // update readings.humidity = 100; readings.temperature = 212.75F; readings.pressure = 950; weatherData.UpdateReadings(readings); Console.ReadLine(); }
public void CanTestConditionWithSuppliedForecast() { Forecast f = new Forecast(); f.PrecipitationProbability = 51; ForecastCondition fc = ForecastCondition.Parse("PrecipitationProbability > 50"); Assert.IsTrue(fc.Test(f)); }
public void GetForecastData(string ticker, int limit) { string query_model = "SELECT model_id FROM stock_model WHERE stock_code = '" + ticker + "'"; List<string[]> model = Database.Query(query_model); if (model.Count <= 0) return; string model_id = model[0][0]; string query = "SELECT value, confi_50, confi_95 FROM model_forecast WHERE model_id='" + model_id + "' AND `order` > " + past.ToString() + " ORDER BY `order` ASC LIMIT " + limit.ToString(); List<string[]> records = Database.Query(query); result.Clear(); for (int i = 0; i < records.Count; i++) { Forecast newForecast = new Forecast(); newForecast.Stock = ticker; newForecast.ForecastVal = Convert.ToDouble(records[i][0]); newForecast.Limit50 = Convert.ToDouble(records[i][1]); newForecast.Limit95 = Convert.ToDouble(records[i][2]); result.Add(newForecast); } Thread.Sleep(2000); Callback.SendResult(result); }
protected void Page_Load(object sender, EventArgs e) { intProfile = Int32.Parse(Request.Cookies["profileid"].Value); oPlatform = new Platforms(intProfile, dsn); oType = new Types(intProfile, dsn); oModelsProperties = new ModelsProperties(intProfile, dsn); oServiceRequest = new ServiceRequests(intProfile, dsn); oForecast = new Forecast(intProfile, dsn); oPage = new Pages(intProfile, dsn); if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "") { intApplication = Int32.Parse(Request.QueryString["applicationid"]); } if (Request.QueryString["pageid"] != null && Request.QueryString["pageid"] != "") { intPage = Int32.Parse(Request.QueryString["pageid"]); } if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "") { intApplication = Int32.Parse(Request.Cookies["application"].Value); } int intPlatform = 0; if (Request.QueryString["id"] != null && Request.QueryString["id"] != "") { intPlatform = Int32.Parse(Request.QueryString["id"]); } if (intPlatform > 0) { intMax = Int32.Parse(oPlatform.Get(intPlatform, "max_inventory1")); if (!IsPostBack) { LoadLists(); LoadFilters(); LoadGroups(intPlatform); } btnProjects.Attributes.Add("onclick", "return MakeWider(this, '" + lstProjects.ClientID + "');"); btnProjectsClear.Attributes.Add("onclick", "return ClearList('" + lstProjects.ClientID + "');"); btnClasses.Attributes.Add("onclick", "return MakeWider(this, '" + lstClasses.ClientID + "');"); btnClassesClear.Attributes.Add("onclick", "return ClearList('" + lstClasses.ClientID + "');"); btnConfidences.Attributes.Add("onclick", "return MakeWider(this, '" + lstConfidences.ClientID + "');"); btnConfidencesClear.Attributes.Add("onclick", "return ClearList('" + lstConfidences.ClientID + "');"); btnEnvironments.Attributes.Add("onclick", "return MakeWider(this, '" + lstEnvironments.ClientID + "');"); btnEnvironmentsClear.Attributes.Add("onclick", "return ClearList('" + lstEnvironments.ClientID + "');"); btnLocations.Attributes.Add("onclick", "return MakeWider(this, '" + lstLocations.ClientID + "');"); btnLocationsClear.Attributes.Add("onclick", "return ClearList('" + lstLocations.ClientID + "');"); lstClasses.Attributes.Add("onchange", "PopulateEnvironmentsList('" + lstClasses.ClientID + "','" + lstEnvironments.ClientID + "',0);"); lstEnvironments.Attributes.Add("onchange", "UpdateListHidden('" + lstEnvironments.ClientID + "','" + hdnEnvironment.ClientID + "');"); imgStart.Attributes.Add("onclick", "return ShowCalendar('" + txtStart.ClientID + "');"); imgEnd.Attributes.Add("onclick", "return ShowCalendar('" + txtEnd.ClientID + "');"); } }
private static async Task GetForcast(dynamic x, double latitude, double longitude) { //if (ForecastRetrieved < DateTime.Now.AddMinutes(5)) //{ // return; //} ForecastApi api = new ForecastApi(x.apikey); forecast = await api.GetWeatherDataAsync(latitude, longitude); ForecastRetrieved = DateTime.Now; }
public async void DarkSky() { var client = new DarkSkyService(Constants.DarkSkyApi); Forecast result = await client.GetTimeMachineWeatherAsync( Convert.ToDouble(locationLatitude.Text), Convert.ToDouble(locationLongitude.Text), DateTimeOffset.Now ); tempature.Text = Convert.ToString(result.Currently.Temperature); tempTitle.Text = result.Currently.Icon.ToUpper().Replace("-", " "); tempIcon.Source = result.Currently.Icon.Replace("-", "") + ".png"; }
public async Task <WeatherData> GetWeatherData() { string key = Configuration["OpenWeatherApiKey"]; Forecast forecast = new Forecast(); WeatherData data = null; //If I call this method asynchronously it'll return null. Problem on the package side? Task getWeatherCityWOCountry = Task.Run(async() => { data = await forecast.GetWeatherDataByCityNameAsync(key, "moscow", "ru", WeatherUnits.Metric); }); getWeatherCityWOCountry.Wait(); return(data); }
public static async Task <string> GetWeather(string address) { IGeocoder geocoder = new GoogleGeocoder(); IEnumerable <Address> addresses = await geocoder.GeocodeAsync(address); var georesult = addresses.First(); Forecast forecast = new Forecast(); var result = forecast.GetWeatherDataByCityNameAsync("a3222c3f65f66410ab8e7604f6d6a8d2", address, "gb", WeatherUnits.imperial); var test = Convert.ToString(result.Result.main.temp); return(test); }
public static bool GetParsedForecast(ref Forecast forecast, dynamic json) { // Initialize results list and current forecast object var results = new List <Prediction>(); for (var i = 0; i < json.DailyForecasts.Count; i++) { results.Add(CreatePrediction(json.DailyForecasts[i])); } forecast.Predictions = results; forecast.Current = results[0]; return(true); }
public string GetSerie(string attribute) { string res = "{"; Forecast F = new Forecast(); res += F.forecastSARIMAindex(attribute); res += "}"; Console.WriteLine(res); //var index = P.readIndex(attribute); return(res); }
private double GetHourlyRain(Forecast allForecastData, int day) { double rainAccumulation = 0; foreach (var hour in allForecastData.Hourly.Hours) { if (hour.Time.Day == day) { rainAccumulation += hour.PrecipitationIntensity; } } return(rainAccumulation); }
private void ListBoxNightForecasts_Tap(object sender, System.Windows.Input.GestureEventArgs e) { ListBox listBox = sender as ListBox; if (listBox.SelectedItem != null) { Forecast forecast = listBox.SelectedItem as Forecast; ShowForecastDescriptionMarquee(string.Format("{0} ({1})", forecast.PredictionForNight, string.Format(AppResources.WeatherUpdatedTime, string.Format("{0} {1}", forecast.DateTime.ToLongDateString(), forecast.DateTime.ToLongTimeString())))); } }
public DemoStats(double[][] dataMatrix) { var transpMatrix = MatrixFunction.TransposeMatrix(dataMatrix); Correlations = new CorrelationsAnalysis(transpMatrix, dataMatrix[0].Length - 1); Regressions = new RegressionAnalysis(dataMatrix, dataMatrix[0].Length - 1); Descriptive = new DescriptiveStatistics[transpMatrix.Length]; for (int i = 0; i < Descriptive.Length; ++i) { Descriptive[i] = new DescriptiveStatistics(transpMatrix[i]); } Forecast = new Forecast(dataMatrix, transpMatrix.Length - 1); }
/// <summary> /// The as forecast entry. /// </summary> /// <param name="forecast"> /// The forecast. /// </param> /// <returns> /// The <see cref="ForecastEntry"/>. /// </returns> public static ForecastEntry AsForecastEntry(this Forecast forecast) { return(new ForecastEntry { Day = forecast.Date, Description = forecast.Desciption, PrecipitationDay = forecast.ProbabilityOfPrecipiation.Daytime, PrecipitationNight = forecast.ProbabilityOfPrecipiation.Nighttime, TemperatureLow = forecast.Temperatures.MorningLow, TemperatureHigh = forecast.Temperatures.DaytimeHigh, TypeId = forecast.WeatherID }); }
private static void Main(string[] args) { Console.WriteLine("\nEXAMPLE 3 : PUB/SUB : CONSUMER"); var connectionFactory = new ConnectionFactory { HostName = "localhost", UserName = "******", Password = "******" }; var connection = connectionFactory.CreateConnection(); var channel = connection.CreateModel(); var queueName = channel.QueueDeclare().QueueName; const string ExchangeName = "example3_forecasts_exchange"; channel.ExchangeDeclare(exchange: ExchangeName, type: ExchangeType.Fanout); channel.QueueBind( queue: queueName, exchange: ExchangeName, routingKey: string.Empty); var consumer = new EventingBasicConsumer(channel); consumer.Received += (sender, eventArgs) => { var body = eventArgs.Body.ToArray(); var forecast = Forecast.FromBytes(body); DisplayInfo <Forecast> .For(forecast) .SetExchange(eventArgs.Exchange) .SetQueue(queueName) .SetRoutingKey(eventArgs.RoutingKey) .SetVirtualHost(connectionFactory.VirtualHost) .Display(Color.Yellow); channel.BasicAck(eventArgs.DeliveryTag, multiple: false); }; channel.BasicConsume( queue: queueName, autoAck: false, consumer: consumer); Console.ReadLine(); }
protected void Page_Load(object sender, EventArgs e) { intProfile = Int32.Parse(Request.Cookies["profileid"].Value); oPage = new Pages(intProfile, dsn); oRequestItem = new RequestItems(intProfile, dsn); oRequest = new Requests(intProfile, dsn); oWorkstation = new Workstations(intProfile, dsn); oApplication = new Applications(intProfile, dsn); oForecast = new Forecast(intProfile, dsn); oFunction = new Functions(intProfile, dsn, intEnvironment); oUser = new Users(intProfile, dsn); if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "") { intApplication = Int32.Parse(Request.QueryString["applicationid"]); } if (Request.QueryString["pageid"] != null && Request.QueryString["pageid"] != "") { intPage = Int32.Parse(Request.QueryString["pageid"]); } if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "") { intApplication = Int32.Parse(Request.Cookies["application"].Value); } if (Request.QueryString["rid"] != "" && Request.QueryString["rid"] != null) { LoadValues(); int intItem = Int32.Parse(lblItem.Text); int intService = Int32.Parse(lblService.Text); int intApp = oRequestItem.GetItemApplication(intItem); string strDeliverable = oApplication.Get(intApp, "deliverables_doc"); if (strDeliverable != "") { panDeliverable.Visible = true; btnDeliverable.Attributes.Add("onclick", "return OpenWindow('NEW_WINDOW','" + strDeliverable + "');"); } if (Request.QueryString["n"] != null && Request.QueryString["n"] != "") { if (!IsPostBack) { LoadWorkstation(); } } else if (Request.QueryString["formid"] == null || Request.QueryString["formid"] == "") { btnNext.Enabled = false; } btnContinue.Attributes.Add("onclick", "return ValidateText('" + txtName.ClientID + "','Please enter a workstation name') && ProcessButton(this) && LoadWait();"); } btnCancel1.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this service request?');"); imgDate.Attributes.Add("onclick", "return ShowCalendar('" + txtDate.ClientID + "');"); }
public static Forecast GetForecast(string accessToken, string userId) { AWSXRayRecorder.Instance.BeginSubsegment("MyBudgetExplorer.Models.Cache.GetForecast()"); try { var binaryFormatter = new BinaryFormatter(); var aesKey = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(userId)); var aesIV = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(userId)); var hash = BitConverter.ToString(aesKey).Replace("-", "").ToLower(); var fileName = $"forecast.{hash}"; var tempFilePath = Path.Combine(Path.GetTempPath(), fileName); byte[] encrypted = null; // Local File Forecast forecast = GetLocalForecast(userId); if (forecast != null) { return(forecast); } // Create Forecast forecast = Forecast.Create(accessToken, userId); // Serialize & Encrypt Forecast using (var ms = new MemoryStream()) { binaryFormatter.Serialize(ms, forecast); encrypted = EncryptAES(ms.ToArray(), aesKey, aesIV); } // Store Local File if (encrypted != null && encrypted.Length > 0) { File.WriteAllBytes(tempFilePath, encrypted); File.SetCreationTimeUtc(tempFilePath, forecast.LastModifiedOn); File.SetLastWriteTimeUtc(tempFilePath, forecast.LastModifiedOn); } return(forecast); } catch (Exception e) { AWSXRayRecorder.Instance.AddException(e); throw; } finally { AWSXRayRecorder.Instance.EndSubsegment(); } }
public bool testInvalidForecast() { Forecast f = new Forecast(); List <Forecast.ForecastData> data = f.getForecast("https://api.weather.gov/gridpoints/INZ/40,70/forecast?units=us"); //if one value is null all is null //only need to check 1 value to exist if (data.Count == 0) { return(true); } return(false); }
public static void Main() { string json = @"{""Date"":""2020-10-23T09:51:03.8702889-07:00"",""TemperatureC"":40,""Summary"":""Hot""}"; Console.WriteLine($"Input JSON: {json}"); Forecast forecastDeserialized = JsonSerializer.Deserialize <Forecast>(json); Console.WriteLine($"Date: {forecastDeserialized.Date}"); Console.WriteLine($"TemperatureC: {forecastDeserialized.TemperatureC}"); json = JsonSerializer.Serialize <Forecast>(forecastDeserialized); Console.WriteLine($"Output JSON: {json}"); }
protected void Page_Load(object sender, EventArgs e) { intProfile = Int32.Parse(Request.Cookies["profileid"].Value); Workstations oWorkstation = new Workstations(0, dsn); OnDemand oOnDemand = new OnDemand(0, dsn); Forecast oForecast = new Forecast(0, dsn); ModelsProperties oModelsProperties = new ModelsProperties(0, dsn); if (Request.QueryString["id"] != null && Request.QueryString["id"] != "") { Functions oFunction = new Functions(0, dsn, intEnvironment); int intWorkstation = Int32.Parse(oFunction.decryptQueryString(Request.QueryString["id"])); int intType = oModelsProperties.GetType(intModelVirtual); DataSet dsSteps = oOnDemand.GetSteps(intType, 1); DataSet ds = oWorkstation.GetVirtual(intWorkstation); if (ds.Tables[0].Rows.Count > 0) { int intAnswer = Int32.Parse(ds.Tables[0].Rows[0]["answerid"].ToString()); int intRemote = Int32.Parse(ds.Tables[0].Rows[0]["remoteid"].ToString()); int intCurrent = Int32.Parse(ds.Tables[0].Rows[0]["step"].ToString()); Workstations workstation = new Workstations(0, dsnRemote); DataSet dsResult = workstation.GetWorkstationVirtualRemoteStatus(intRemote); if (dsResult.Tables[0].Rows.Count > 0) { int intStep = Int32.Parse(dsResult.Tables[0].Rows[0]["step"].ToString()); int intID = Int32.Parse(dsResult.Tables[0].Rows[0]["id"].ToString()); if (intStep == 1) { oWorkstation.AssignHost(intWorkstation, dsnRemote, dsnAsset, intEnvironment, dsnZeus); Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "completed", "<script type=\"text/javascript\">window.onload = new Function(\"redirectWait();\");<" + "/" + "script>"); } else if (intCurrent < intStep) { oOnDemand.UpdateStepDoneWorkstation(intWorkstation, intCurrent, oOnDemand.GetStep(intStep, "done"), 0, false, false); oWorkstation.NextVirtualStep(intWorkstation); Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "completed", "<script type=\"text/javascript\">window.onload = new Function(\"redirect();\");<" + "/" + "script>"); } else if (intCurrent == dsSteps.Tables[0].Rows.Count) { oWorkstation.NextVirtualStep(intWorkstation); //SqlHelper.ExecuteNonQuery(dsnRemote, CommandType.Text, "UPDATE cv_virtual_workstations SET deleted = 1 WHERE id = " + intID.ToString() + " AND deleted = 0"); oForecast.UpdateAnswerCompleted(intAnswer); oWorkstation.UpdateVirtualCompleted(intWorkstation); Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "completed", "<script type=\"text/javascript\">window.onload = new Function(\"redirect();\");<" + "/" + "script>"); } } } Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "completed", "<script type=\"text/javascript\">window.onload = new Function(\"redirectWait();\");<" + "/" + "script>"); } }
private async void DisplayForecastDetails() { Forecast forecast = await ForecastProcessor.GetForecast(); int above20DegreeDays = ForecastProcessor.GetNumberOfDaysWithTempAbove(20, forecast); int sunnyDays = ForecastProcessor.GetNumberOfWithWeatherCondition("Clear", forecast); WeatherMap.Text += "In next 5 days" + "\n"; WeatherMap.Text += "--------------" + "\n"; WeatherMap.Text += "The number of days have temperature above 20 degrees = " + above20DegreeDays + "\n"; WeatherMap.Text += "The number of sunny days = " + sunnyDays + "\n"; WeatherMap.Text += "\n N.B 'Clear' days are taken as 'Sunny' days."; }
private void UpdateFromForecast(Forecast forecast) { bool isMetric = RegionInfo.CurrentRegion.IsMetric; //Convert to either Celcius or Fahrenheit based on regional settings. double regionalTemperature = (isMetric) ? forecast.Temperature - 273.15 : forecast.Temperature - 9 / 5 - 459.67; this.Temperature = $"{regionalTemperature:F0} " + ((isMetric) ? "°C" : "°F"); this.ForecastDate = forecast.ForecastDate; this.WeatherDescription = forecast.WeatherDescription; this.WeatherIconUrl = forecast.WeatherIconUrl; this.WeatherCode = forecast.WeatherCode; }
private Forecast MapToRowForecast(SqlDataReader reader, bool isFahrenheit) { Forecast forecast = new Forecast() { IsFahrenheit = isFahrenheit, ParkCode = Convert.ToString(reader["parkCode"]), //parkCode Low = Convert.ToInt32(reader["low"]), //low High = Convert.ToInt32(reader["high"]), //high Day = Convert.ToInt32(reader["fiveDayForecastValue"]), ForecastDescription = Convert.ToString(reader["forecast"]) }; return(forecast); }
public ObjectId?StoreForecast(Forecast forecast) { try { var client = new MongoClient(_connectionString); IMongoDatabase database = client.GetDatabase(_mongoDbName); IMongoCollection <Forecast> collection = database.GetCollection <Forecast>(_mongoDbCollectionName); collection.InsertOne(forecast); return(forecast.Id); } catch { return(null); } }
public Forecast MapResponse(ForecastIOResponse response) { var forecast = new Forecast(); forecast.Latitude = response.latitude; forecast.Longitude = response.longitude; forecast.MinimumTemperature = response.daily.data.ElementAt(0).temperatureMin; forecast.MaximumTemperature = response.daily.data.ElementAt(0).temperatureMax; forecast.PrecipitationProbability = response.daily.data.ElementAt(0).precipProbability; forecast.CloudCover = response.daily.data.ElementAt(0).cloudCover; forecast.Date = DateTime.Now; return(forecast); }
private Forecast ConvertReaderToForecast(SqlDataReader reader) { // Create a Forecast Forecast forecast = new Forecast(); forecast.ParkCode = Convert.ToString(reader["parkCode"]); forecast.Day = Convert.ToInt32(reader["fiveDayForecastValue"]); forecast.Low = Convert.ToInt32(reader["low"]); forecast.High = Convert.ToInt32(reader["high"]); forecast.Weather = Convert.ToString(reader["forecast"]); forecast.Advice = this.GetAdvice(forecast); return(forecast); }
public List <ChartPoint> ChartValues(Forecast forecastValues) { List <ChartPoint> chartPoints = new List <ChartPoint>(); if (forecastValues != null) { foreach (var forecastItem in forecastValues.Items) { var label = forecastItem.DtTxt.ToShortTimeString(); chartPoints.Add(new ChartPoint((int)forecastItem.Main.Temp, label)); } } return(chartPoints); }
protected void btnComplete_Click(Object Sender, EventArgs e) { int intResourceWorkflow = Int32.Parse(lblResourceWorkflow.Text); int intResourceParent = oResourceRequest.GetWorkflowParent(intResourceWorkflow); oResourceRequest.UpdateWorkflowStatus(intResourceWorkflow, 3, true); oOnDemandTasks.AddSuccess(intResourceParent, "VMware", Int32.Parse(ddlSuccess.SelectedItem.Value), txtComments.Text); oOnDemandTasks.UpdateVirtualIIComplete(intRequest, intItem, intNumber); Forecast oForecast = new Forecast(intProfile, dsn); oForecast.UpdateAnswerFinished(Int32.Parse(lblAnswer.Text)); oResourceRequest.CloseWorkflow(intResourceWorkflow, intEnvironment, strBCC, 0, dsnServiceEditor, true, intResourceRequestApprove, intAssignPage, intViewPage, dsnAsset, dsnIP); Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "reload", "<script type=\"text/javascript\">RefreshOpeningWindow();window.close();<" + "/" + "script>"); }
protected override void StartState() { base.StartState(); Forecast forecast = new Forecast(); forecast.Economic = m_controller.EconomicForecaster.Forecast(Game); forecast.Water = m_controller.Forecaster.Forecast(Game); Game.Forecast = forecast; Game.ForEachPlayer(delegate(Player p) { p.ResetForNextTurn(); }); UpdateAllStatus(); }
public bool testEmptyForecast() { Forecast f = new Forecast(); List <Forecast.ForecastData> data = f.getForecast(""); //if one value is null all is null //only need to check 1 value to exist if (data.Count == 0) { return(true); } return(false); }
/// <summary> /// </summary> public ForecastPage(Forecast forecast) { _graph = new SkiaGraph(forecast.Days.Select(hour => new GraphIndex { Hide = false, Y = (float)hour.Day.Average, ImageId = hour.Day.Condition.Image(true), Label = XameteoL10N.OnlyDayMonth(hour.Date) }).Take(7).ToList()); Items = forecast.Days; InitializeComponent(); BindingContext = this; }
public void FirstTestMethodForCftB() { var revenueList = new List <RevenueDTO>(); revenueList.Add(new RevenueDTO { Month = 1, Revenue = 11602710.6694915 }); var forecast = new Forecast(0.7, 0.15, 0.1, 1, revenueList); var list = forecast.RevenueLinkedList.ToList(); var b = list[0].CftB; Assert.AreEqual(b, 0); }
protected void Page_Load(object sender, EventArgs e) { AuthenticateUser(); intProfile = Int32.Parse(Request.Cookies["profileid"].Value); oForecast = new Forecast(intProfile, dsn); btnAdd.Attributes.Add("onclick", "return ValidateText('" + txtPath.ClientID + "','Please enter a path')" + " && ValidateDate('" + txtFirst.ClientID + "','Please enter a valid date')" + " && CheckRetention461('" + ddlRetention.ClientID + "','" + txtRetention.ClientID + "')" + " && CheckFrequency461('" + ddlFrequency.ClientID + "','" + txtFrequency.ClientID + "')" + ";"); txtPath.Focus(); ddlFrequency.Attributes.Add("onchange", "ChangeFrequency461(this,'" + divFrequency.ClientID + "');"); imgArchiveDate.Attributes.Add("onclick", "return OpenCalendar('" + txtFirst.ClientID + "');"); }
public ForecastViewModel (INavigation navigation, Forecast forecast) { this.forecast = forecast; this.navigation = navigation; ScheduledGroupCount = forecast.ScheduledGroupsCount.ToString (); if (forecast.ScheduledGroupsCount == 1) ScheduledGroupText = "event"; else ScheduledGroupText = "events"; Reason = forecast.Reason; GroupList = forecast.GroupList; }
public async Task<Forecast> GetForecastAsync (Position location) { var openGroupForecast = await _openGroupMapService.Get7DayForecastAsync (location); var forecast = new Forecast () { Location = location }; var daysClean = 0; var dtf = new DateTimeFormatInfo (); foreach (var forecastItem in openGroupForecast.Forecasts) { var weather = forecastItem.WeatherList.FirstOrDefault (); var date = new DateTime (1970, 1, 1).AddSeconds (forecastItem.Dt); forecast.GroupList.Add (new GroupViewTemplate { GroupCondition = weather.Description, DayAbbreviation = dtf.GetAbbreviatedDayName (date.DayOfWeek), EventStart = Convert.ToInt32(forecastItem.Temperature.Max) + "º", EventEnd = Convert.ToInt32(forecastItem.Temperature.Min) + "º", Icon = GetWeatherIcon (weather.Main) }); } foreach (var forecastItem in openGroupForecast.Forecasts) { var date = new DateTime (1970, 1, 1).AddSeconds (forecastItem.Dt); if (date.Date.Date < DateTime.Now.Date.Date) continue; var weatherForToday = forecastItem.WeatherList [0]; forecast.BadWeatherDay = date; forecast.Reason = ConvertReason (weatherForToday.Main); forecast.ReasonDescription = weatherForToday.Description; if (WeatherIsBad (weatherForToday)) break; daysClean++; } forecast.ScheduledGroupsCount = daysClean; return forecast; }
private void OnGenerateForecast(object sender, RoutedEventArgs e) { // generate random forecast var data = new List<Forecast>(); int days = (int)_days.SelectedItem; var rnd = new Random(); for (int i = 0; i < days; i++) { double temp = rnd.NextDouble() * 40 - 10; var forecast = new Forecast { GeneralForecast = (GeneralForecast)rnd.Next(Enum.GetValues(typeof(GeneralForecast)).Length), TemperatureLow = temp, TemperatureHigh = temp + rnd.NextDouble() * 15, Percipitation = rnd.Next(10) > 5 ? rnd.NextDouble() * 10 : 0 }; data.Add(forecast); } DataContext = data; }
public static void BeginFetchForecasts(List<Place> mjesta) { //prođemo sva mjesta tako da instanciramo forecast objekta samo ako još nema ni jedne instance s istim parametrom foreach (var mjesto in mjesta) { var forecastold = forecasts.Where(i => i.Param == mjesto.Param); if (forecastold.Any()) { mjesto.Forecast = forecastold.Take(1).SingleOrDefault(); } else { Forecast forecast = new Forecast(mjesto.Id, mjesto.Title, mjesto.Param); mjesto.Forecast = forecast; forecasts.Add(forecast); } var placeold = places.Where(i => i.Id == mjesto.Id).Take(1).SingleOrDefault(); if (placeold != null) { if (placeold.Param.ToLower().Trim() != mjesto.Param.ToLower().Trim()) { placeold.Param = mjesto.Param; placeold.Forecast = mjesto.Forecast; } if (placeold.Title.ToLower().Trim() != mjesto.Title.ToLower().Trim()) { placeold.Title = mjesto.Title; placeold.Forecast = mjesto.Forecast; } } else { places.Add(mjesto); } } BeginRefreshForecasts(forecasts); }
public abstract void UpdateForecast(Forecast forecast);
public ForecastFilter(Forecast forecast) { ForecastId = forecast.Id; }
public ForecastPage(RootPage rootPage, Forecast forecast) { this._rootPage = rootPage; _forecast = forecast; BindingContext = new ForecastViewModel (Navigation, _forecast); NavigationPage.SetHasNavigationBar (this, false); var masterGrid = new Grid { RowDefinitions = new RowDefinitionCollection { new RowDefinition{ Height = new GridLength (0.3, GridUnitType.Star) }, new RowDefinition{ Height = new GridLength (0.3, GridUnitType.Star) }, new RowDefinition{ Height = new GridLength (0.4, GridUnitType.Star) } }, ColumnDefinitions = new ColumnDefinitionCollection{ new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) } } }; var forecastListview = new ListView (); var forecastListviewItemTemplate = new DataTemplate (typeof(ImageCell)); forecastListviewItemTemplate.SetBinding (ImageCell.TextProperty, "ItemTemplateTextProperty"); forecastListviewItemTemplate.SetValue(ImageCell.TextColorProperty, Color.FromHex("#3498DB")); forecastListviewItemTemplate.SetBinding (ImageCell.DetailProperty, "ItemTemplateDetailProperty"); forecastListviewItemTemplate.SetValue(ImageCell.DetailColorProperty, Color.White); forecastListviewItemTemplate.SetBinding (ImageCell.ImageSourceProperty, "Icon"); forecastListview.ItemTemplate = forecastListviewItemTemplate; forecastListview.SetBinding<ForecastViewModel> (ListView.ItemsSourceProperty, vm => vm.GroupList); var refreshImage = new ImageButton () { Image = "Refresh", ImageHeightRequest = 70, ImageWidthRequest = 70, BorderColor = Color.Transparent, VerticalOptions = LayoutOptions.Start, BackgroundColor = Color.Transparent }; refreshImage.Clicked += (object sender, EventArgs e) => { /*_rootPage.ShowLoadingDialogAsync ();*/ }; var topGrid = new Grid {RowDefinitions = new RowDefinitionCollection { new RowDefinition{ Height = new GridLength (1, GridUnitType.Star) } }, ColumnDefinitions = new ColumnDefinitionCollection { new ColumnDefinition{ Width = new GridLength (0.8, GridUnitType.Star) }, new ColumnDefinition{ Width = new GridLength (0.2, GridUnitType.Star) }, } }; topGrid.Children.Add (CreateForecastStatusStackLayout (), 0, 0); topGrid.Children.Add (refreshImage, 1, 0); masterGrid.Children.Add (topGrid, 0, 0); masterGrid.Children.Add (CreateMiddleStackLayout (), 0, 1); masterGrid.Children.Add (forecastListview, 0, 2); Content = masterGrid; }
public abstract void AddForecast(Forecast forecast);
public void GetForecastResult(int periodCount, int count, bool isMulti = false) { var nextPeriod = GetNextPeriod(); if (isMulti) { var isHad = ProduceData.GetForecastByperiodAndType(nextPeriod, "LostBall"); if (isHad > 0) return; } var allRedBall = new List<string>(); var allBlueBall = new List<string>(); for (int i = 1; i < 34; i++) { if (i < 10) { allRedBall.Add("0"+i); } allRedBall.Add(i.ToString()); } for (int i = 1; i < 17; i++) { if (i < 10) { allBlueBall.Add("0"+i); } allBlueBall.Add(i.ToString()); } var dicRedLost = new Dictionary<string, int>(); var dicBlueLost = new Dictionary<string, int>(); var redSql = @"SELECT top 1 * FROM dbo.V_RedBall WHERE redBall='{0}' ORDER BY periodId DESC "; foreach (var i in allRedBall) { var _redSql = string.Format(redSql, i); var db = sqlHelper.ExecReturnDataSet(_redSql).Tables[0]; if (db != null && db.Rows.Count > 0) { dicRedLost.Add(i, int.Parse(db.Rows[0]["periodId"].ToString())); } } var blueSql = @"SELECT * FROM dbo.lottery WHERE blueBall1='{0}' ORDER BY periodId DESC "; foreach (var j in allBlueBall) { var _blueSql = string.Format(blueSql, j); var db = sqlHelper.ExecReturnDataSet(_blueSql).Tables[0]; if (db != null && db.Rows.Count > 0) { dicBlueLost.Add(j, int.Parse(db.Rows[0]["periodId"].ToString())); } } //获得红球 var redList = dicRedLost.OrderBy(r => r.Value).Take(6).OrderBy(r=>r.Key).ToList(); var blueList = dicBlueLost.OrderBy(r => r.Value).Take(1).ToList(); var forecast=new Forecast() { periodId = nextPeriod, redBall1 = redList[0].Key.ToString(), redBall2 = redList[1].Key.ToString(), redBall3 = redList[2].Key.ToString(), redBall4 = redList[3].Key.ToString(), redBall5 = redList[4].Key.ToString(), redBall6 = redList[5].Key.ToString(), benifitCount = 0, blueBall1 = blueList[0].Key.ToString(), forecastType = "LostBall", CostMoney = 2 }; var list=new List<Forecast>(); list.Add(forecast); ProduceData.CreateForecast(list); }
public void GetForecastResult(int periodCount, int count, bool isMulti = false) { var nextPeriod = GetNextPeriod(); if (isMulti) { var isHad = ProduceData.GetForecastByperiodAndType(nextPeriod, "ZGetRadomForecast"); if (isHad > 0) return; } var foreCastSql = "SELECT redBall FROM dbo.V_ForeCastRedBall where periodId='" + nextPeriod + "' GROUP BY redBall"; var allBlueBall = new List<string>(); for (int i = 1; i < 17; i++) { if (i < 10) { allBlueBall.Add("0"+i); } allBlueBall.Add(i.ToString()); } var dicBlueLost = new Dictionary<string, int>(); var blueSql = @"SELECT * FROM dbo.lottery WHERE blueBall1='{0}' ORDER BY periodId DESC"; foreach (var j in allBlueBall) { var _blueSql = string.Format(blueSql, j); var db = sqlHelper.ExecReturnDataSet(_blueSql).Tables[0]; if (db != null && db.Rows.Count > 0) { dicBlueLost.Add(j, int.Parse(db.Rows[0]["periodId"].ToString())); } } //获得红球 var blueList = dicBlueLost.OrderBy(r => r.Value).ToList(); var redDb = sqlHelper.ExecReturnDataSet(foreCastSql).Tables[0]; var listRandom = new List<Forecast>(); if (redDb != null && redDb.Rows.Count > 0) { var dbCount = redDb.Rows.Count; var singalCount = dbCount/6; var list = redDb.AsEnumerable().Select(x => x["redBall"].ToString()).ToList(); var random = new Random(); for (int i = 0; i < singalCount; i++) { var redList=new List<string>(); for (int a = 0; a < 6; a++) { int len = list.Count(); var r = random.Next(0,len); redList.Add(list[r]); list.RemoveAt(r); } redList = redList.OrderBy(r => r).ToList(); var forecast=new Forecast() { periodId = nextPeriod, redBall1 = redList[0].ToString(), redBall2 = redList[1].ToString(), redBall3 = redList[2].ToString(), redBall4 = redList[3].ToString(), redBall5 = redList[4].ToString(), redBall6 = redList[5].ToString(), blueBall1 = blueList[random.Next(0,blueList.Count)].Key.ToString(), forecastType = "ZGetRadomForecast", CostMoney = 2, benifitCount = 0, hitBlue = "0", hitRed = "0", isLottery = 0, hitLottery = "0" }; listRandom.Add(forecast); } ProduceData.CreateForecast(listRandom); } }
public override void UpdateForecast(Forecast forecast) { _context.Entry(forecast).State = EntityState.Modified; }
public override void AddForecast(Forecast forecast) { _context.Forecasts.Add(forecast); }
public void ShouldRequirePrecipitationProbabilityLessThanOrEqualTo100() { Forecast f = new Forecast(); f.PrecipitationProbability = 101; }
public void ShouldRequirePrecipitationProbabilityGreaterThanOrEqualToZero() { Forecast f = new Forecast(); f.PrecipitationProbability = -1; }
public void ShouldHavePrecipitationProbabilityProperty() { Forecast f = new Forecast(); f.PrecipitationProbability = 40; Assert.AreEqual(40, f.PrecipitationProbability); }