public Junction MapXmlToDomain(XmlJunction xmlJunction, IList<SplitTrack> subTracks) { SplitTrack defaultTrack = subTracks.First(subTrack => xmlJunction.BranchDefaultId.Equals(subTrack.Id)); SplitTrack altTrack = subTracks.First(subTrack => xmlJunction.BranchAlternateId.Equals(subTrack.Id)); return new Junction(xmlJunction.Id, defaultTrack, altTrack, xmlJunction.Direction); }
//exactly same as x.browser private static void UpdateManifest(IList<Services.Data.ExtensionManifestDataModel> found, IExtensionManifest ext) { if (found != null && found.Count() > 0) { ext.IsExtEnabled = found.First().IsExtEnabled; ext.LaunchInDockPositions = (ExtensionInToolbarPositions)found.First().LaunchInDockPositions; ext.FoundInToolbarPositions = (ExtensionInToolbarPositions)found.First().FoundInToolbarPositions; } }
public CurrencyRateViewMode(IList<CurrencyRate> rates) { var dollarSellingRate = rates.First(r => r.Type == TradeType.Selling && r.CurrencyName == "Dollar"); var euroSellingRate = rates.First(r => r.Type == TradeType.Selling && r.CurrencyName == "Euro"); var dollarBuyingRate = rates.First(r => r.Type == TradeType.Buying && r.CurrencyName == "Dollar"); var euroBuyingRate = rates.First(r => r.Type == TradeType.Buying && r.CurrencyName == "Euro"); SellingUsDollar = new RateKeyPair(dollarSellingRate.RateId){ExchangePrice = dollarSellingRate.ExchangePrice}; SellingEuro = new RateKeyPair(euroSellingRate.RateId) { ExchangePrice = euroSellingRate.ExchangePrice}; BuyingUsDollar = new RateKeyPair(dollarBuyingRate.RateId) {ExchangePrice = dollarBuyingRate.ExchangePrice}; BuyingEuro = new RateKeyPair(euroBuyingRate.RateId) { ExchangePrice = euroBuyingRate.ExchangePrice }; }
private Section CreateSection(IList<string> lines, int level) { string title = null; var headingMarker = new String('#', level) + " "; if (lines.First().StartsWith(headingMarker)) { title = lines.First().TrimStart('#').Trim(); lines.RemoveAt(0); } var furtherLevelMarkers = new String('#', level + 1); return lines.Any(x => x.StartsWith(furtherLevelMarkers)) ? new Section(level, title, BreakDownSection(lines, level + 1).ToList()) : new Section(level, title, string.Join(Environment.NewLine, lines)); }
public Statistics(IList<IVehicle> vehicles, bool removeOutliers = true) { if (vehicles == null || !vehicles.Any()) throw new ArgumentException("Vehicles is null or count is 0. Must be greater than 0"); _vehicles = vehicles; _outlierVehicles = new List<OutlierVehicle>(); Make = _vehicles.First().Make; Model = _vehicles.First().Model; if (removeOutliers) { RemoveOutliers(); } }
public Measure GetHourlyEnergyMeasure(IList<Measure> sourceMeasures, string hourMeasureSource, string hourDataVariable) { var dataVariable = hourDataVariable; var measurePercentage = 1; var plant = sourceMeasures.First().Plant; var reliability = 0; var resolution = getHourResolution(); var source = hourMeasureSource; var utcDate = sourceMeasures.First().UtcDate; var utcHour = sourceMeasures.First().UtcHour; var utcMinute = 00; var utcSecond = 00; var value = getValue(sourceMeasures); return new Measure(plant, source, dataVariable, utcDate, utcHour, utcMinute, utcSecond, value, measurePercentage, reliability, resolution); }
/// <summary> /// Sort the items by their priority and their index they currently exist in the collection /// </summary> /// <param name="files"></param> /// <returns></returns> public static IList<IClientDependencyFile> SortItems(IList<IClientDependencyFile> files) { //first check if each item's order is the same, if this is the case we'll make sure that we order them //by the way they were defined if (!files.Any()) return files; var firstPriority = files.First().Priority; if (files.Any(x => x.Priority != firstPriority)) { var sortedOutput = new List<IClientDependencyFile>(); //ok they are not the same so we'll need to sort them by priority and by how they've been entered var groups = files.GroupBy(x => x.Priority).OrderBy(x => x.Key); foreach (var currentPriority in groups) { //for this priority group, we'll need to prioritize them by how they are found in the files array sortedOutput.AddRange(currentPriority.OrderBy(files.IndexOf)); } return sortedOutput; } //they are all the same so we can really just return the original list since it will already be in the //order that they were added. return files; }
private FeedResult FeedResult(IList<SyndicationItem> items) { var settings = Settings.GetSettings<FunnelWebSettings>(); Debug.Assert(Request.GetOriginalUrl() != null, "Request.GetOriginalUrl() != null"); var baseUri = Request.GetOriginalUrl(); var feedUrl = new Uri(baseUri, Url.Action("Recent", "Wiki")); return new FeedResult( new Atom10FeedFormatter( new SyndicationFeed(settings.SiteTitle, settings.SearchDescription, feedUrl, items) { Id = baseUri.ToString(), Links = { new SyndicationLink(baseUri) { RelationshipType = "self" } }, LastUpdatedTime = items.Count() == 0 ? DateTime.Now : items.First().LastUpdatedTime }), items.Max(i => i.LastUpdatedTime.LocalDateTime)) { ContentType = "application/atom+xml" }; }
public static MapRepresentation Create(IOidStrategy oidStrategy, HttpRequestMessage req, ContextFacade contextFacade, IList<ContextFacade> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) { var memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, req, c, flags))).ToList(); IObjectFacade target = contexts.First().Target; MapRepresentation mapRepresentation; if (format == Format.Full) { var tempProperties = new List<OptionalProperty>(); if (!string.IsNullOrEmpty(contextFacade?.Reason)) { tempProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, contextFacade.Reason)); } var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName(oidStrategy)); tempProperties.Add(dt); var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues.ToArray())); tempProperties.Add(members); mapRepresentation = Create(tempProperties.ToArray()); } else { mapRepresentation = Create(memberValues.ToArray()); } mapRepresentation.SetContentType(mt); return mapRepresentation; }
public void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets) { if (IsHtmlFile && completionSets.Any()) { var bottomSpan = completionSets.First().ApplicableTo; if (!JScriptEditorUtil.IsInJScriptLanguageBlock(_lbm, bottomSpan.GetStartPoint(bottomSpan.TextBuffer.CurrentSnapshot))) { // This is an HTML statement completion session, so do nothing return; } } // TODO: Reflect over the ShimCompletionSet to see where the Description value comes from // as setting the property does not actually change the value. var newCompletionSets = completionSets .Select(cs => cs == null ? cs : new ScriptCompletionSet( cs.Moniker, cs.DisplayName, cs.ApplicableTo, cs.Completions .Select(c => c == null ? c : new Completion( c.DisplayText, c.InsertionText, DocCommentHelper.ProcessParaTags(c.Description), c.IconSource, c.IconAutomationText)) .ToList(), cs.CompletionBuilders)) .ToList(); completionSets.Clear(); newCompletionSets.ForEach(cs => completionSets.Add(cs)); }
public MainWindow() { InitializeComponent(); Loaded += (sender, e) => ClearValue(SizeToContentProperty); _allControllerViewModels = (from type in GetType().Assembly.GetTypes() where !type.IsInterface && typeof(IController).IsAssignableFrom(type) let viewModel = new ControllerViewModel((IController)Activator.CreateInstance(type)) orderby viewModel.SortIndex, viewModel.Library, viewModel.Description select viewModel).ToList(); _allControllerViewModels.First().IsChecked = true; ControllerGroups.ItemsSource = _allControllerViewModels.GroupBy(viewModel => viewModel.Library); _allResolutionViewModels = new[] { new ResolutionViewModel(800, 600, 50, 42), new ResolutionViewModel(1024, 768, 64, 54), new ResolutionViewModel(1280, 1024, 80, 73), new ResolutionViewModel(1440, 900, 90, 64), }; _allResolutionViewModels.Last( res => res.Width <= SystemParameters.PrimaryScreenWidth && res.Height <= SystemParameters.PrimaryScreenHeight).IsChecked = true; Resolutions.ItemsSource = _allResolutionViewModels; RunResults.ItemsSource = _runResults; }
private void CheckFirstAndLastPoint(IList<Point> points) { if (this.DistanceIsTooSmall(points.Last(), points.First())) { points.RemoveAt(points.Count - 1); } }
public IList<DepthPointEx> Filter(IList<DepthPointEx> points) { IList<DepthPointEx> result = new List<DepthPointEx>(); if (points.Count > 0) { var point = new DepthPointEx(points.First()); result.Add(point); foreach (var currentSourcePoint in points.Skip(1)) { if (!PointsAreClose(currentSourcePoint, point)) { point = new DepthPointEx(currentSourcePoint); result.Add(point); } } if (result.Count > 1) { CheckFirstAndLastPoint(result); } } return result; }
public int Update(AdoAdapter adapter, string tableName, IList<IDictionary<string, object>> data, IDbTransaction transaction, IList<string> keyFields) { int count = 0; if (data == null) throw new ArgumentNullException("data"); if (data.Count < 2) throw new ArgumentException("UpdateMany requires more than one record."); if (keyFields.Count == 0) throw new NotSupportedException("Adapter does not support key-based update for this object."); if (!AllRowsHaveSameKeys(data)) throw new SimpleDataException("Records have different structures. Bulk updates are only valid on consistent records."); var table = adapter.GetSchema().FindTable(tableName); var exampleRow = new Dictionary<string, object>(data.First(), HomogenizedEqualityComparer.DefaultInstance); var commandBuilder = new UpdateHelper(adapter.GetSchema()).GetUpdateCommand(tableName, exampleRow, ExpressionHelper.CriteriaDictionaryToExpression( tableName, GetCriteria(keyFields, exampleRow))); using (var connectionScope = ConnectionScope.Create(transaction, adapter.CreateConnection)) using (var command = commandBuilder.GetRepeatableCommand(connectionScope.Connection)) { var propertyToParameterMap = CreatePropertyToParameterMap(data, table, command); foreach (var row in data) { foreach (var kvp in row) { propertyToParameterMap[kvp.Key].Value = kvp.Value ?? DBNull.Value; } count += command.ExecuteNonQuery(); } } return count; }
public static MapRepresentation Create(HttpRequestMessage req, IList<ContextSurface> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) { OptionalProperty[] memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(req, c, flags))).ToArray(); INakedObjectSurface target = contexts.First().Target; MapRepresentation mapRepresentation; if (format == Format.Full) { var tempProperties = new List<OptionalProperty>(); if (flags.SimpleDomainModel) { var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName()); tempProperties.Add(dt); } if (flags.FormalDomainModel) { var links = new OptionalProperty(JsonPropertyNames.Links, new[] { Create(new OptionalProperty(JsonPropertyNames.Rel, RelValues.DescribedBy), new OptionalProperty(JsonPropertyNames.Href, new UriMtHelper(req, target.Specification).GetDomainTypeUri())) }); tempProperties.Add(links); } var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues)); tempProperties.Add(members); mapRepresentation = Create(tempProperties.ToArray()); } else { mapRepresentation = Create(memberValues); } mapRepresentation.SetContentType(mt); return mapRepresentation; }
private void CheckFirstAndLastPoint(IList<DepthPointEx> points) { if (PointsAreClose(points.Last(), points.First())) { points.RemoveAt(points.Count - 1); } }
public MultilayerPerceptron(int numInputs, int numOutputs, IList<int> hiddenLayerSizes) { if (numInputs <= 0) throw new NeuralNetworkException($"Argument {nameof(numInputs)} must be positive; was {numInputs}."); if (numOutputs <= 0) throw new NeuralNetworkException($"Argument {nameof(numOutputs)} must be positive; was {numOutputs}."); if (hiddenLayerSizes == null || !hiddenLayerSizes.Any()) throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} cannot be null or empty."); if (hiddenLayerSizes.Any(h => h <= 0)) { var badSize = hiddenLayerSizes.First(h => h <= 0); var index = hiddenLayerSizes.IndexOf(badSize); throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} must contain only positive " + $"values; was {badSize} at index {index}."); } NumInputs = numInputs; NumOutputs = numOutputs; HiddenLayerSizes = hiddenLayerSizes.ToArray(); Weights = new double[hiddenLayerSizes.Count + 1][]; for (var i = 0; i < hiddenLayerSizes.Count + 1; i++) { if (i == 0) Weights[i] = new double[(numInputs + 1) * hiddenLayerSizes[0]]; else if (i < hiddenLayerSizes.Count) Weights[i] = new double[(hiddenLayerSizes[i-1] + 1) * hiddenLayerSizes[i]]; else Weights[i] = new double[(hiddenLayerSizes[hiddenLayerSizes.Count - 1] + 1) * numOutputs]; } }
public IList<Point> Filter(IList<Point> points) { IList<Point> result = new List<Point>(); if (points.Count == 0) { return result; } var point = new Point(points.First()); result.Add(point); foreach (var currentSourcePoint in points.Skip(1)) { if (!this.DistanceIsTooSmall(currentSourcePoint, point)) { point = new Point(currentSourcePoint); result.Add(point); } } if (this.checkBoundary && result.Count > 1) { CheckFirstAndLastPoint(result); } return result; }
public bool CanExecute(IList<string> documentIds) { if (documentIds == null || documentIds.Count == 0) return false; return string.IsNullOrEmpty(documentIds.First()) == false; }
public static QueryExpressionSyntax WithAllClauses( this QueryExpressionSyntax query, IList<SyntaxNode> allClauses) { var fromClause = (FromClauseSyntax)allClauses.First(); return query.WithFromClause(fromClause).WithBody(query.Body.WithAllClauses(allClauses.Skip(1))); }
public static List<PlayEvent> Create(IList<Event> events, string homeTeam) { var penalties = new List<PlayEvent>(); var penaltyEvents = events.Where(e => e.Class == "Penalty"); foreach (var penaltyEvent in penaltyEvents) { var penaltyStartTime = GameTimeCalculator.Calculate(penaltyEvent.Period, penaltyEvent.TimePeriod); var penaltyEndTime = CalculatePenaltyEndTime(penaltyEvent.Description, penaltyEvent.Period, penaltyEvent.TimePeriod); Logger.Debug(string.Format("Game {0} S {1} E {2} ET {3}", events.First().GameId, penaltyStartTime.ToClockTime(), penaltyEndTime.ToClockTime(), penaltyEvent.Description)); penalties.Add(new PlayEvent { StartTime = penaltyStartTime, EndTime = penaltyEndTime, Class = penaltyEvent.Class, Description = penaltyEvent.Description, HomeTeam = penaltyEvent.Team == homeTeam, }); } return penalties; }
public static RatioValue Calculate(IList<double> numerators, IList<double> denominators) { if (numerators.Count != denominators.Count) { throw new ArgumentException(); } if (numerators.Count == 0) { return null; } if (numerators.Count == 1) { return new RatioValue(numerators.First()/denominators.First()); } var statsNumerators = new Statistics(numerators); var statsDenominators = new Statistics(denominators); var ratios = new Statistics(numerators.Select((value, index) => value/denominators[index])); // The mean ratio is the average of "ratios" weighted by "statsDenominators". // It's also equal to the sum of the numerators divided by the sum of the denominators. var meanRatio = statsNumerators.Sum()/statsDenominators.Sum(); // Helpers.Assume(Math.Abs(mean - stats.Mean(statsW)) < 0.0001); // Make sure the value does not exceed the bounds of a float. float meanRatioFloat = (float)Math.Min(float.MaxValue, Math.Max(float.MinValue, meanRatio)); return new RatioValue { Ratio = meanRatioFloat, StdDev = (float) ratios.StdDev(statsDenominators), DotProduct = (float) statsNumerators.Angle(statsDenominators), }; }
public virtual Span Handle(IList<Token> tokens, Options options) { var now = options.Clock(); var span = new Span(now, now.AddSeconds(1)); var grabberTokens = tokens .SkipWhile(token => token.IsNotTaggedAs<Grabber>()) .ToList(); if (grabberTokens.Any()) { span = grabberTokens.GetAnchor(options); } var scalarRepeaters = tokens .TakeWhile(token => token.IsNotTaggedAs<Pointer>()) .Where(token => token.IsNotTaggedAs<SeparatorComma>()) .ToList(); var pointer = tokens.First(token => token.IsTaggedAs<Pointer>()); for (var index = 0; index < scalarRepeaters.Count - 1; index++) { var scalar = scalarRepeaters[index]; var repeater = scalarRepeaters[++index]; span = Handle(new List<Token>{ scalar, repeater, pointer}, span, options); } return span; }
/// <summary> /// Constructor. /// </summary> public SubmissionCandidatesViewModel( User user, IList<Commit> commits, Func<Commit, string> commitUrlBuilder, Checkpoint checkpoint, Model.Projects.Submission latestSubmission, ITimeZoneProvider timeZoneProvider) { User = user; Checkpoint = checkpoint; Candidates = commits .OrderByDescending(commit => commit.PushDate) .ThenByDescending(commit => commit.CommitDate) .Select ( commit => new SubmissionCandidateViewModel ( commit, commitUrlBuilder(commit), latestSubmission?.CommitId == commit.Id, commit == commits.First(), timeZoneProvider ) ).ToList(); }
private static string tryGetInstanceName(MethodInfo methodInfo, IList<object> arguments) { return methodInfo.Name.StartsWith("GetNamed", StringComparison.InvariantCultureIgnoreCase) && arguments.Any() ? Convert.ToString(arguments.First()) : null; }
public AnimatedSprite(Texture2D texture, EntityType entityType, IList<AnimationSequence> animations, AnimationActions initialAnimationAction, Rectangle worldPosition, Vector2 speed = new Vector2(), Vector2 direction = new Vector2(), bool isCollidable = false, int collisionOffset = 0) : base(texture, entityType, worldPosition, speed: speed, direction: direction, isCollidable: isCollidable, collisionOffset: collisionOffset) { Animations = animations; CurrentAnimation = Animations.First(a => a.AnimationAction == initialAnimationAction); }
private void InternalSubmitData(IList<MongodbItem> items) { if (items == null || items.Count == 0) return; var databaseName = items.First().DatabaseName; try { if (CachedMongoServer == null) return; var database = CachedMongoServer.GetDatabase(databaseName); foreach (var item in items) { var collection = database.GetCollection(item.TableName); collection.Insert(item.Data); } } catch (Exception ex) { LocalLoggingService.Exception("MongodbInsertService.InternalSubmitData<{0}> error: {1}", databaseName, ex.Message); } }
public ActionResult AprobarOrden(int id, IList<DetalleOrdenRecargaPrepago> detalleOrden, decimal MontoTotalRecargas, string indicadorGuardar, string DocumentoReferencia, string Observaciones) { ViewModel viewmodel = new ViewModel(); detalleOrden.First().documentoOrden = DocumentoReferencia; detalleOrden.First().observacionesOrden = Observaciones; if (indicadorGuardar == "Aprobar") { if (repOrden.AprobarOrden(detalleOrden.ToList(), MontoTotalRecargas)) { viewmodel.Title = "Prepago / Ordenes de Recarga / Detalle de la Orden"; viewmodel.Message = "Orden Aprobada."; viewmodel.ControllerName = "OrdenRecargaPrepago"; viewmodel.ActionName = "FilterReview"; return RedirectToAction("GenericView", viewmodel); //return RedirectToAction("DetalleOrden", new { id = id, idOrden = idOrden }); } else { viewmodel.Title = "Prepago / Ordenes de Recarga / Detalle de la Orden"; viewmodel.Message = "Falló el proceso de aprobación de la Orden."; viewmodel.ControllerName = "OrdenRecargaPrepago"; viewmodel.ActionName = "FilterReview"; return RedirectToAction("GenericView", viewmodel); } } else { if (repOrden.GuardarOrden(detalleOrden.ToList(), MontoTotalRecargas)) { viewmodel.Title = "Prepago / Ordenes de Recarga / Detalle de la Orden"; viewmodel.Message = "Datos de la Orden actualizados."; viewmodel.ControllerName = "OrdenRecargaPrepago"; viewmodel.ActionName = "FilterReview"; return RedirectToAction("GenericView", viewmodel); //return RedirectToAction("DetalleOrden", new { id = id, idOrden = idOrden }); } else { viewmodel.Title = "Prepago / Ordenes de Recarga / Detalle de la Orden"; viewmodel.Message = "Falló el proceso de guardado de la Orden."; viewmodel.ControllerName = "OrdenRecargaPrepago"; viewmodel.ActionName = "FilterReview"; return RedirectToAction("GenericView", viewmodel); } } }
public bool CanExecute(IList<DocumentViewModel> documents) { if (documents == null || documents.Count == 0) return false; var document = documents.First(); return document != null && document.CollectionType != BuiltinCollectionName.Projection; }
public DataProviderViewModel(ExperimentViewModel experimentViewModel, IServiceLocator serviceLocator) { this.serviceLocator = serviceLocator; _experimentViewModel = experimentViewModel; ViewModel = experimentViewModel; dataProviders = serviceLocator.GetAllInstances<IDataProvider>().ToList(); selectedDataProvider = dataProviders.First(); }